The filter_var() function filters a variable with the specified filter. This function is used to both validate and sanitize the data.
Syntax :-
filter_var(var, filtername, options)Parameters: This function accepts three parameters and are described below:
- var : It is the required field. It denotes the variable to filter.
- filtername : It is used to specify the ID or name of the filter to use. Default is FILTER_DEFAULT, which results in no filtering. It is optional field.
- options : It is used to specify one or more flags/options to use. Check each filter for possible options and flags. It is also optional field.
-
Sanitize a string :
In the below example we sanitize a string
Example:-
Output :-PHP <?php $str = "<h1>GeeksforGeeks!</h1>"; $newstr = filter_var($str, FILTER_SANITIZE_STRING); echo $newstr; ?>
GeeksforGeeks!
-
Validate an Integer :
The below example uses the filter_var() function to check if the variable $int is an integer. If $int is an integer, the output of the code below will be: "Integer is valid". If $int is not an integer, the output will be: "Integer is not valid":
Example:-
Output :-PHP <?php $int = 200; if (filter_var($int, FILTER_VALIDATE_INT) === 0 || !filter_var($int, FILTER_VALIDATE_INT) === false) { echo("Integer is valid"); } else { echo("Integer is not valid"); } ?>
Integer is valid
-
Validate an IP Address :
The following example uses the filter_var() function to check if the variable $ip is a valid IP address:
Example :-
Output :-PHP <?php $ip = "129.0.0.1"; if (!filter_var($ip, FILTER_VALIDATE_IP) === false) { echo("$ip is a valid IP address"); } else { echo("$ip is not a valid IP address"); } ?>
129.0.0.1 is a valid IP address
-
Sanitize and Validate an Email Address :
The following example uses the filter_var() function to first remove all illegal characters from the $email variable, then check if it is a valid email address:
Example :-
Output :-PHP <?php $email = "[email protected]"; // Remove all illegal characters from email $email = filter_var($email, FILTER_SANITIZE_EMAIL); // Validate e-mail if (!filter_var($email, FILTER_VALIDATE_EMAIL) === false) { echo("$email is a valid email address"); } else { echo("$email is not a valid email address"); } ?>
[email protected] is a valid email address
-
Sanitize and Validate a URL :
The following example uses the filter_var() function to first remove all illegal characters from a URL, then check if $url is a valid URL:
Example :-
Output :-PHP <?php $url = "https://www.geeksforgeeks.org/"; // Remove all illegal characters from a url $url = filter_var($url, FILTER_SANITIZE_URL); // Validate url if (!filter_var($url, FILTER_VALIDATE_URL) === false) { echo("$url is a valid URL"); } else { echo("$url is not a valid URL"); } ?>
https://www.geeksforgeeks.org/ is a valid URL