Sanitizing data in PHP

PHP 5.2 arrived with some functions for data validation like filter_input() that allows you to sanitize the data or simply validate it.

Sanitizing vs Validating

The difference between validating and sanitizing the data with that function is that validation only return true or false if the data is valid meanwhile the other method makes the data to be valid and returns it but there is a dark side in the sanitation, if the string is short enough or simply all characters are invalid you’ll get an empty string.

Sanitizing

It works like doing a $_GET[‘var’] or $_POST[‘var’] but optionally the developer has the chance of sanitize the data. Very handy to make our websites a bit more secure.

$var = filter_input(INPUT_GET, 'search');

However the previous code doesn’t increase security in any way it just acts like a simple $_GET[‘search’];

But this function allows more arguments to be used like the sanitize filters, that is when it becomes useful to our purposes.

Lets see how we can sanitize ID’s mostly used in database queries and how to sanitize strings as example.

$id = filter_input(INPUT_GET, 'id', FILTER_SANITIZE_NUMBER_INT);
$user_name = filter_input(INPUT_POST, 'id', FILTER_SANITIZE_STRING);

Validating

The data validation using their respective validate filters only will return true or false if the input data is valid or not.

$is_valid = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);
$is_valid = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_IP);

You may also like...

4 Responses

  1. Anto says:

    Muy bueno este tuto, aunque podrías pasarlo a español por favor?

    Gracias!

  2. Persocom says:

    I didn’t know about these functions. I always used preg_replace to sanitize data.

    Many thanks!

  3. Marina says:

    You have really interesting blog, keep up posting such informative posts!

Leave a Reply

Your email address will not be published. Required fields are marked *