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?

Link to comment
Share on other sites

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()

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.