PHP | filter_var() Function (original) (raw)
Last Updated : 18 Nov, 2019
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.
Return Value: It returns the filtered data on success, or FALSE on failure. Below are some different applications of filter_var() function:
- **Sanitize a string :**In the below example we sanitize a string Example:- PHP ` GeeksforGeeks!"; newstr=filtervar(newstr = filter_var(newstr=filtervar(str, FILTER_SANITIZE_STRING);
echo $newstr;
?>` Output :-
GeeksforGeeks! - **Validate an Integer :**The below example uses the filter_var() function to check if the variable intisaninteger.Ifint is an integer. If intisaninteger.Ifint 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:- PHP ` ` Output :-
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 :- PHP ` ` Output :-
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 :- PHP ` email=filtervar(email = filter_var(email=filtervar(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");
}
?>` Output :-
gfg@example.com 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 :- PHP ` url=filtervar(url = filter_var(url=filtervar(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");
}
?>` Output :-
https://www.geeksforgeeks.org/ is a valid URL
Reference:https://www.php.net/manual/en/function.filter-var.php