Tip: How to clean all your incoming POST and GET data in one line

Status
Not open for further replies.

Stanley

Banned
Jun 24, 2006
3,399
43
0
San Diego
This is a very simple way to clean all your $_POST or $_GET fields:


For AJAX requests: foreach ($_POST as $key => $value) $_POST[$key]=trim(strip_tags(urldecode($value)));

For standard forms: foreach ($_POST as $key => $value) $_POST[$key]=trim(strip_tags($value));


The script cycles through all your $_POST variables, converts them to their original format, strips out any possible code, and then gets rid of unnecessary spaces at the beginning or the end of the strings.

I figured someone here might find it useful. It's a very simple line of code but it gets the job done.
 


Won't work if you have an array in your form..

<input type="text" name="bla[1]" value="1" />
<input type="text" name="bla[2]" value="2" />

trim(); won't work on that array. So you should add if (is_array(..))

And then ofcourse if you want to allow HTML input you'd have to bypass this cleaning phase.
 
Here's a convoluted mess for PHP that supports arrays:

Code:
foreach ($_POST as $key => $value) if(is_array($value))foreach($value as $key2 => $value2) $_POST[$key][$key2] =trim(strip_tags($value2)); else $_POST[$key]=trim(strip_tags($value));

Please don't use this...ever.

-the mole
 
Status
Not open for further replies.