The filter_var() function in PHP is a powerful and versatile tool used for validating and sanitizing data and believe like humans, the code needs to be sanitized as well. Jokes apart! So, I what I was saying that this function is particularly useful making sure or to ascertain that the data received from external sources, such as user input, is safe and valid. Given the importance of data validation in web applications, understanding how to effectively use filter_var() is crucial. In this guide about php filter_var() I have given code examples for each use-case but one thing should be kept in mind that I have used [email protected] just to explain the case further and to help you understand that you better use your own email address. In case you are just a practitioner you could use [email protected]. Make sure to follow along and I believe if you followed the this code guide with examples I am pretty sure you would get it hammered into your memory and understand it fully. So let’s begin without losing on our time.
(I) Understanding filter_var()
Like we say, first thing first, and we must understand something that we are doing. If you are newbie you should get that too. So, funamentally and basically the filter_var() function filters a variable with a specified filter. It would take in two primary parameters: the variable you want to filter and the filter type. Hey, there’s an option too, you can also pass an array of options to customize the filtering process.
filter_var(mixed $variable, int $filter = FILTER_DEFAULT, array|int $options = 0): mixed
- $variable: This is the value you wish to filter.
- $filter: This is an optional integer parameter that specifies the type of filter to apply. If no filter is provided,
- FILTER_DEFAULT is used, which is equivalent to FILTER_UNSAFE_RAW.
- $options: This is an optional parameter. It can either be an associative array of options or a bitwise disjunction of flags.
The function returns the filtered data on success or false if the filter fails.
(II) Commonly Used Filters
The filter_var() function has the tendency to supports a wide range of filters, each serving a specific purpose. Below are some of the most commonly used filters:
(i) FILTER_VALIDATE_INT: Validates if the value is an integer.
$int = "123";
if (filter_var($int, FILTER_VALIDATE_INT) !== false) {
echo "The value is a valid integer.";
} else {
echo "The value is not a valid integer.";
}
(ii) FILTER_VALIDATE_EMAIL: Validates if the value is a valid email address we have used our own domain name/email address for explanation you could replace it with yours, hopefully.
$email = "[email protected]";
if (filter_var($email, FILTER_VALIDATE_EMAIL) !== false) {
echo "The email address is valid.";
} else {
echo "The email address is not valid.";
}
(iii) FILTER_VALIDATE_URL: Validates if the value is a valid URL.
$url = "https://www.laramatic.com";
if (filter_var($url, FILTER_VALIDATE_URL) !== false) {
echo "The URL is valid.";
} else {
echo "The URL is not valid.";
}
(iv) FILTER_SANITIZE_STRING: Removes tags and encodes special characters from a string.
$string = "<h1>Hello, World!</h1>";
$sanitizedString = filter_var($string, FILTER_SANITIZE_STRING);
echo $sanitizedString; // Output: Hello, World!
(v) FILTER_SANITIZE_EMAIL: Removes all illegal characters from an email address.
$email = "[email protected]";
$sanitizedEmail = filter_var($email, FILTER_SANITIZE_EMAIL);
echo $sanitizedEmail; // Output: [email protected]
(vi) FILTER_SANITIZE_URL: Removes all illegal characters from a URL
$url = "https://www.laramatic.com";
$sanitizedURL = filter_var($url, FILTER_SANITIZE_URL);
echo $sanitizedURL; // Output: https://www.laramatic.com
(III) Using Options with filter_var()
The filter_var() function would allows us for far even more than that custom options through the use of options. These options enable developers to tailor the filtering process to meet specific needs.
See the example below with FILTER_VALIDATE_INT
$options = [
"options" => [
"min_range" => 1,
"max_range" => 100
]
];
$int = 50;
if (filter_var($int, FILTER_VALIDATE_INT, $options) !== false) {
echo "The value is within the specified range.";
} else {
echo "The value is not within the specified range.";
}
In this example, the integer value is validated to ensure that it falls within the range of 1 to 100.
(IV) Error Handling and filter_var()
One of the advantages of using filter_var() is its ability to return false when the validation fails. This allows developers to implement error handling mechanisms effectively. By checking if the function’s return value is false, one can easily determine whether the data passed the validation or not.
See this code examole for error handling and filter_var()
$email = "invalid-email";
if (filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
echo "Invalid email address.";
} else {
echo "Valid email address.";
}
In the baove code example or case, if the email address is not valid, an error message will be displayed.
(V) Best Practices for Using filter_var()
- Always validate user input – Before processing any data submitted by users, it is essential to validate it using filter_var() to ensure its correctness.
- Use appropriate filters – Choose the correct filter that matches the data type you are working with, such as FILTER_VALIDATE_EMAIL for email addresses or FILTER_VALIDATE_URL for URLs.
- Handle errors effectively- Implement error handling to manage cases where validation fails, thereby preventing potential issues in your application.
- Sanitize data when necessary- Use the sanitization filters provided by filter_var() to clean data and remove unwanted characters.












