Home » PHP » PHP Filters
This tutorial helps you learn how to use PHP Filter to validate and filter data. So, let us begin.
You can use PHP filters for validating and sanitizing external input.
This extension has many functions needed to check user input. It has been designed to make data validation easier and quicker.
You can use the filter_list() function to list what the PHP filter extension provides:
<table>
<tr>
<td>Filter Name</td>
<td>Filter ID</td>
</tr>
<?php
foreach (filter_list() as $id =>$filter) {
echo '<tr><td>' . $filter . '</td><td>' . filter_id($filter) . '</td></tr>';
}
?>
</table>
External input is received by many web applications. External input/data can be:
This function is used for both validating and sanitizing data.
It filters a single variable with a specified filter. The filter_var() function takes two pieces of data:
The example below uses the filter_var() function for removing all HTML tags from a string:
<?php
$str = "<h1>Hello World!</h1>";
$newstr = filter_var($str, FILTER_SANITIZE_STRING);
echo $newstr;
?>
The example below uses the filter_var() function for checking if the variable $int is an integer. In case $int is an integer, then the output of the code below will be: "Integer is valid". On the other hand, if $int is not an integer, "Integer is not valid" will be the output:
<?php
$int = 100;
if (!filter_var($int, FILTER_VALIDATE_INT) === false) {
echo("Integer is valid");
} else {
echo("Integer is not valid");
}
?>
In the example here, the filter_var() function has been used for checking if the variable $ip is a valid IP address:
<?php
$ip = "127.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");
}
?>
In the example here, the filter_var() function has been used for first removing all illegal characters from the $email variable, then checking if it is a valid email address:
<?php
$email = "ada@developerstutorial.com";
// 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");
}
?>