Jump to content

Sanitizing database input without storing bashslashes in the database?


DWilliams

Recommended Posts

I'm building a fairly simple PHP page to interface with the MySQL database maintained by our software at work (which I don't have the source code to). If you enter special characters into said software they enter into the database just as typed (no backslashes preceding special characters). When I'm writing PHP scripts, I always call mysql_real_escape_string on whatever I'm going to be using in a query. This normally works fine but it stores backslashes in the database. If I call stripslashes on it when I pull it back out everything is fine.

 

Now, for this script I'm making now, I can't really have the backslashes being inserted into the database since they actually show up in the program when somebody pulls that data up.

 

How can I protect against SQL injection without storing backslashes in the database?

If you end up with the escape \ characters stored in the database, then you are escaping the data twice. The \ characters should only exist in the query. When the query is executed, the escaped special characters are treated as the literal un-escaped character and only the special character is inserted.

 

Since it is unlikely that you are intentionally escaping data twice in your code, it is likely that magic_quotes_gpc is ON and php is automatically escaping the data first.

 

If you can, you need to turn off magic_quotes_gpc. However, since you won't always be on a server where you will be able to turn it off, you must actually check if it is on and use stripslashes() first -

 

if (get_magic_quotes_gpc()) {
    $var = stripslashes($var);
}
$var = mysql_real_escape_string($var);

 

If your data is never expected to contain a \ character as actual data that someone entered, you could unconditionally use stripslashes() before you use mysql_real_escape_string()

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.