PHP Filters

This tutorial helps you learn how to use PHP Filter to validate and filter data. So, let us begin.

 

What is PHP Filter?

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>

 

Why Use Filters?

External input is received by many web applications. External input/data can be:

  • User input from a form
  • Cookies
  • Web services data
  • Server variables
  • Database query results

 

PHP filter_var() Function

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 variable you want to check
  • The type of check to use

 

Sanitize a String

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;
?>

 

Validate an Integer

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");
}
?>

 

Validate an IP Address

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");
}
?>

 

Sanitize and Validate an Email 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");
}
?>