Sanitize PHP Variables

The most important aspect of website security is how you validate and sanitize variables. Validation is to try to fit a variable into a pattern. Usually if the validation fails then the variable is rejected. To sanitize a variable is to find unwanted characters in a variable. When you find such characters usually you just strip them off and the variable is accepted.

Generally, the easiest a variable can be modified the harder validation and sanitizing it should undergo. Thus variables coming from $_REQUEST variables should be examined with highest priority.

First you try to validate a variable and if it is not possible you sanitize it. It is not always possible to validate a variable because not all variables can match an useful regular expression.

In this article we will talk about sanitizing variables. We will demonstrate how to sanitize variables using a popular PHP class from CakePHP framework:

Most of the class methods can be used directly out of the box. Let's have some examples.

First, let's include the file and instantiate the class:

$sanitize = new Sanitize;

Next, let's imagine we have a variable $name coming from POST request:

$name = $sanitize->paranoid($_POST['name'],array('\'', '\&'));

I have used the method 'paranoid' for sanitizing it. This method allows whitelisting of custom characters as an array in the second argument of the method. Note that these characters have to be escaped in most cases. In my case, I have whitelisted ' and &. So if the name is 'Joe & Jane O'Hara' it will not strip any characters of it. Once the variable goes through the method it is returned clean, clear and safe :)

Next, let's imagine we have some comments coming from the POST request too.

$comment = $sanitize->stripScripts($_POST['comment']);

If we have used the paranoid method here it will render the comments unreadable... unless we whitelist most characters. That's why CakePHP developers have come with a better option to just strip scripts tags. 

Check the rest of the methods and you might find other useful to your needs too. Of course, be careful with PHP variable sanitizing. It is essential to website security but it may prevent you from gathering correctly the data.

blog comments powered by Disqus