Data sanitization in PHP

I’m going to show you a simple, yet effective way to clean your data (sanitize it) before you attempt to insert into your database. I prefer using the $_REQUEST superglobal array instead of just $_POST or $_GET.

$_REQUEST encompasses $_GET, $_POST, and $_COOKIE inside one array.

We take the $_REQUEST array and do a foreach() loop over it assigning $k for the key and $v for the value of the array element we’re currently looping over. We then re-assign the value to the array after we have cleaned it.

foreach($_REQUEST as $k => $v) {
    $_REQUEST[$k] = addslashes($v);
}

You’re not limited to just the $_REQUEST array, you can use this method on any array that you need to perform specific actions on. There’s even functions built-in to PHP such as array_walk() that allow you to iterate over an array issuing callbacks on each element. The choice is up to you, I just prefer the simplest method.

Sanitization is not the same as validation.

The elephants instep,
Bryan

Related reading

One Response to “Data sanitization in PHP”


Leave a Reply