Data validation and sanitization in PHP

Today we are going to see about the validating and sanitizing the data in PHP. What is different between validating and sanitizing the data.

Validating is used to check the data is perfect or not, for example passing the integer value in query-string.  It will validate the data its proper or not and the data will not be changed or remove unwanted characters.

Sanitizing is use to clean-up the data and modify by removing unwanted characters. For example instead of passing the integer value in query-string,  If we are passing string its clean the data by removing unwanted characters.

How its possible in PHP ?

PHP have a concept call Data filtering, which has types of filters.

Types of filters

  1. Validate filters
  2. Sanitize filters

As we already discussed about the Validate and Sanitize, we will step-into simple example. Validating and Sanitizing the “$i” variable in our code.

Validate integer value

<?php
// assigning varaible with ineterger value
$i = 10;

// validating the data its proper or not with filter_var function with ID (FILTER_VALIDATE_INT)
// If its true return valid or else invalid message
echo (filter_var($i,FILTER_VALIDATE_INT)) ? "valid" : "invalid";

Above code will return valid message. Now change the data ‘a1’ in $i variable and check, it will return invalid message.

Sanitize integer value

<?php
// assigning varaible with ineterger value
$i = 'a10';

// Clean the data base on Sanitize filter id mentioned in the filter_var function
echo (filter_var($i,FILTER_SANITIZE_NUMBER_INT)) ? "valid" : "invalid";

Output will be  valid, because its remove the invalid data based one the filter id. You can also check below links for filter ID details for Validate and Sanitize data.

http://www.php.net/manual/en/book.filter.php

Share