Forum Moderators: coopster

Message Too Old, No Replies

mysql real escape string placement in code

different methods may require different placement

         

php4U

9:28 pm on Nov 29, 2007 (gmt 0)

10+ Year Member



A while ago I posted some code, and eelixduppy suggested that I use mysql_real_escape_string to escape my POST variables to prevent injection attacks. I now have had a chance to go back and look into this again. A search of the forum turned up many many results here, and I found a snippet that was posted by eelixduppy.

if(get_magic_quotes_gpc()) {
$_POST = array_map('stripslashes',$_POST);
}
$_POST = array_map('mysql_real_escape_string',$_POST);

From reading the php manual the code above would be a shorthand version of having to name all the variables posted like so mysql_real_escape_string($var1, $var2), since it references $_POST in the array_map. Is that correct? It should cover all POSTED values.

This is essentially the same as what I found in a tutorial prior to finding it here, and the writer included $_GET and $_COOKIE as well. My question is where to place this portion of code because I want it to work right? In the article with the similar code it said

"How to parse out mySQL injection techniques, this can be done with a few lines of code at the top of every page. Usually you
would just write these in a file and include it in all your php files."

I wanted to clarify that the shorthand method can be placed at the top (I don't see a problem with it), because other methods in the php manual show the exact function mysql_real_escape_string going right after the SQL query as the documentation states or custom fuctions being written to "clean" data. It seems like it would be much easier to use the code above, and cover all your posted variables all at once. Thank you for clarification.

PHP_Chimp

9:34 pm on Nov 29, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



if(get_magic_quotes_gpc()) {
$_POST = array_map('stripslashes',$_REQUEST);
}
$_POST = array_map('mysql_real_escape_string',$_REQUEST);

Will apply the stiptslashes and escape string to everything, is you are not only using POST you may want to use REQUEST instead.
As this code is applied to all of the $_POST (in your example)you should be able to call it before any of your sql stuff, as php will then have already run all of the $_POST array through these functions before you start to use the results.

php4U

1:47 am on Dec 6, 2007 (gmt 0)

10+ Year Member



Thank you PHP_Chimp I didn't think there would be a problem calling this at the top.