PHP Filters -Validation and Sanitization

PHP JSON and Callback functions

In this article, you will learn some useful PHP topics as per title, Filters, and Callback functions. Let’s start with the filters.

PHP Filters

PHP filters are used to sanitize and validate the input data.

Sanitization: To Remove any illegal characters from the input data.

Validation: Process of determining if the input data is in proper form.

PHP filters make sure sanitization and validation of data before sending in the request.

Why Sanitization and Validation is important?

Suppose you have an input field on your webpage, where the user can type its address. The hackers can send any script in that input field that can go to the server through request and allow the hacker to crack the system, Sanitization does not allow any script to run on the server-side.

On the other hand, suppose you have a login webpage, that requires an email and password from the user. Validation checks if the email field is filled with a valid format email and password field minimum and maximum length is not violated.

PHP Filter Extension

PHP filter extension is designed to make the validation of data quicker and easier. The PHP filter extension contains many functions built-in that helps to check the input data with ease.

filter_list function in PHP returns all the functions available in the filter extension.

 <?php
  foreach (filter_list() as $id =>$filter) {
    echo '<tr><td>' . $filter . '</td><td>' . filter_id($filter) . '</td></tr>';
  }
  ?>

What are the sources where filtration of data is required?

Following sources can input data externally and needs filtration.

  • Input fields in a form
  • Cookies
  • Data of web services
  • Server variables
  • Results of Database Queries

Filter_var function in PHP

This function both sanitize and filter the data stored in the variable. It accepts two parameters. The first parameter is the variable on which you want to apply the filter. The second parameter is the type of filter to apply to the variable. We will now learn some important filter types available in PHP.

How to sanitize a string in PHP?

FILTER_SANITIZE_STRING filter removes all the HTML tags from the string. The web attackers can send scripts as part of the HTML tag’s attributes. Therefore, the HTML tags are harmful to allow in the string. Look at the following example.

<?php
$str = "<h1>Hello World!</h1>";
$newstr = filter_var($str, FILTER_SANITIZE_STRING);
echo $newstr;
?>

How to Validate an Integer in PHP?

FILTER_VALIDATE_INT checks if the number is an integer or not. The second parameter holds the filter of the filer_var function and the first parameter holds the number. Go through the example below.

<?php
$int = 100;

if (!filter_var($int, FILTER_VALIDATE_INT) === false) {
  echo("Integer is valid");
} else {
  echo("Integer is not valid");
}
?>

Note: The filter_var function with FILTER_VALIDATE_INT consider 0 as a non-integer number. So, if you need to include 0 in the integers, you can modify the if the condition of the above example to allow the 0.

How to validate IP Addresses in PHP?

FILTER_VALIDATE_IP filter checks for the valid IP address. The first parameter is the IP address and the second parameter is the name of the filter in the filter_var function.

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

How to sanitize and validate Email in PHP?

filter_var performs both validation and sanitization of email passed as a second parameter to this function. To sanitize the email, use FILTER_SANITIZE_EMAIL first with the filer_var function, and then for validation of email, use FILTER_VALIDATE_EMAIL filter. Look at the example below.

<?php
$email = "john.doe@example.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");
}
?>

How to sanitize URL in PHP?

Pass the URL as the first parameter to the filer_var function and FILTER_VALIDATE_URL as the second parameter. It will remove all the illegal characters from the URL. It is very useful to filter.

<?php
$url = "https://www.w3schools.com";

// Remove all illegal characters from a url
$url = filter_var($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");
}
?>

What is an Exception and how to throw an exception in PHP?

An exception is an object that tells some error is occurs during the execution of the script. PHP functions and classes throw exceptions and user-defined functions can also throw exceptions.

Exceptions are an efficient way to stop a function without producing wrong results at the end.

The throw keyword sends exceptions. Try catch block captures the exceptions thrown by code block. If the exceptions are not captured, it will give an uncaught exception fatal error.

Try block consist of the block of code to allow execution. Catch block executes only when the try block throws an exception. You can get information about the exception in the catch block using the exception object. Look at the following example in which the division by 0 exceptions is thrown and captured in the catch block.

<?php
function divide($dividend, $divisor) {
  if($divisor == 0) {
    throw new Exception("Division by zero");
  }
  return $dividend / $divisor;
}

try {
  echo divide(5, 0);
} catch(Exception $e) {
  echo "Unable to divide.";
}
?>

For a complete reference to filters, you can refer here.

PHP JSON and Callback functions

Stay up-to-date about PHP!

We don’t spam!

en English
X
Scroll to Top