View Full Version : MySQL injection prevention code trouble

02-08-2006, 11:15 PM
In a different forum, I had asked how to secure my mysql queries when using user input, and they replied that this code protects from it.

function traverse ( &$arr )
if ( !is_array ( $arr ) )

foreach ( $arr as $key => $val )
is_array ( $arr[$key] ) ? traverse ( $arr[$key] ) : ( $arr[$key] = addslashes ( $arr[$key] ) );
$gpc = array ( &$_GET, &$_POST, &$_COOKIE );
traverse ( $gpc );
The only thing is Im not very familiar with the php in this code and Im having a hard time deciphering it line by line. I know what the script does when its all done, but im not sure what it wants sent to it and im kinda fuzzy as to what a foreach loop is and what all the ampersands are for.
Any help is appreciated, Thanks:)

02-08-2006, 11:22 PM
... Why noy just use mysql_real_escape_string() (http://php.net/mysql_real_escape_string) ?

02-08-2006, 11:48 PM
... Why noy just use mysql_real_escape_string() (http://php.net/mysql_real_escape_string) ?
Probably becasue ive never seen that before, thanks.:thumbsup:
I would still like it if someone could explain that code to me though

02-09-2006, 02:24 AM
Its a recursive function that if magic_quotes_gpc is turned off goes though and addslashes() all GET POST and COOKIE data (you could change that to mysql_real_escape_string() if you wished).

It also checks if any of the GPC data is itself an array and if so does the same to them, it does that by calling itself, thats the recursive bit.

Its confusing as the writer seems to like control structures without braces which annoy some and confuse the rest of us ;)

EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum