What is filter_var?
filter_var() is a PHP function used to filters a variable with the help of a specified filter. In PHP programming language we can use filter_var() function to validate and sanitize a data such as an email id, IP address etc.
Basic Syntax of filter_var() Function
filter_var ( mixed $variable [, int $filter = FILTER_DEFAULT [, mixed $options ]] ) : mixed
Parameters
variable |
It is the value which needed to be filtered. Note: Scalar values are converted to string internally before getting filtered. |
filter | It is an optional parameter which represents the name or ID of the filter to be used. Default FILTER_DEFAULT will be used if this parameter is neglected. This will result in no filtering. |
options | Also, an optional parameter, It specifies single or multiple flags/option to be used, This parameter checks for possible flags and option for each filter |
Return Value
If successful it returns filtered value otherwise FALSE in the case fo failure
PHP Filter_var () Example:
This program is an example to validate and sanitize data using Filter_var function
<!DOCTYPE html>
<html>
<body>
<?php
// Variable to check
$email = "test@test.com";
// Remove all illegal characters from email
$email = filter_var($email, FILTER_SANITIZE_EMAIL);
// Validate e-mail
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo("$email is a valid email address");
} else {
echo("$email is not a valid email address");
}
?>
</body>
</html>
Output
test@test.com is a valid email address