The PHP filter_var() function filters a variable with the specified filter. This function can be used to both validate and sanitize data. It can be used to filter various types of data, such as validating email addresses, URLs, and more. It's commonly used for input validation and security to ensure that the data you're working with meets certain criteria
filter_var(variable, filter, options);
- variable: The variable to filter. Required.
- filter: The ID or name of the filter to use. Optional. The default filter is FILTER_DEFAULT, which results in no filtering.
- options: One or more flags/options to use. Optional. Check each filter for possible options and flags.
Sanitize a string:
$string = "This is a string with some special characters: *&$^#@!"; // Remove all special characters from the string. $sanitizedString = filter_var($string, FILTER_SANITIZE_STRING); // Output the sanitized string. echo $sanitizedString;
This example code is designed to check if a given string, represented by the variable $int, can be converted to an integer and whether that integer falls within the range of 10 to 100.
FLTER_FLAG_RANGE_LOW | FILTER_FLAG_RANGE_HIGH:
These are flags used in conjunction with FILTER_VALIDATE_INT to indicate that the validation should include a range check.
$int = "10"; // Check if the integer is within the range of 10 to 100. if (filter_var($int, FILTER_VALIDATE_INT, FILTER_FLAG_RANGE_LOW | FILTER_FLAG_RANGE_HIGH, array("min_range" => 10, "max_range" => 100))) { echo "The integer is within the range of 10 to 100."; } else { echo "The integer is not within the range of 10 to 100."; }
This example sanitizes and validates the user input before using it in the application. This helps to prevent malicious code from being injected into the application.
$userInput = $_POST["user_input"]; // Remove all special characters from the user input. $sanitizedInput = filter_var($userInput, FILTER_SANITIZE_STRING); // Check if the sanitized input is valid. if (filter_var($sanitizedInput, FILTER_VALIDATE_EMAIL)) { // The sanitized input is a valid email address. } elseif (filter_var($sanitizedInput, FILTER_VALIDATE_URL)) { // The sanitized input is a valid URL. } else { // The sanitized input is not valid. }
Conclusion
The PHP filter_var() function is a powerful tool that can be used to validate and sanitize data. It is important to use this function to protect your application from malicious input.