Clean Variables in PHP

Posted on Wednesday July 27, 2011 / by Eric Potvin

Cleaning input variables is often a step developers skip or forget. This step can be important when it's time to log user activities, save data to the database, or any other important actions your code needs to execute. Clean variables are important in order to prevent against all kinds of different malicious intent, such as SQL Injections.

The easy way to clean variables passed via $_POST and $_GET is to set the proper directives in the php.ini file:

magic_quotes_gpc = Off
magic_quotes_runtime = Off

If you can't modify the php.ini, there's a simple way to fix this issue. The main idea of cleaning input variables is pretty simple and it comes down to escaping single and double quotes.

Here's a simple function that will sanitize variables:

function cleanPost($val) {
	if(!isset($_POST[$val])) {
		$_POST[$val] = NULL;
		return;
	}
	$_POST[$val] = trim(htmlentities($_POST[$val], ENT_QUOTES, 'UTF-8'));
}

For example, we have to insert into the database this string:

$_POST['comment'] = "This is a long string with \"quotes\" and single 'quotes' including a <b>bold</b> tag";

If you don't use "addslasches" to sanitize this variable, you will have SQL errors and some users might take advantage of this vulnerability.

To fix this string, simply use:

cleanPost('comment');

This will return:

"This is a long string with &quot;quotes&quot; and single &#039;quotes&#039; including a &lt;b&gt;bold&lt;/b&gt; tag"

If you feel lazy, you can also use the following code:

function clean($val) {
	return trim(htmlentities($val, ENT_QUOTES, 'UTF-8'));
}
$_POST = array_map('clean', $_POST);