php/mysql escaping backslashes
January 26, 2012 4:01 AM   Subscribe

Php question: mysql_real_escape_string is turning '\6' (and I assume any other \(number combination) into a single character '' where it's in my code, but not when the same string is passed through $_POST. Is this a behaviour of magic_quotes (currently on) or something else - and without the ability to change global php settings, what can I do about it?

The code I'm working with sets a hard-coded password when setting up a database (password changed, obviously):

$examplepass = mysql_real_escape_string("EXAMPLE_\6");
mysql_query("INSERT INTO Example_Users (
'$examplepass '

Looking at the query before it's run, this is putting "EXAMPLE_" into the database.

Putting "EXAMPLE_\6" into the login form, then running it through mysql_real_escape_string, gives "EXAMPLE_\\6", which (obviously) doesn't match.
posted by monkey closet to Computers & Internet (6 answers total)
With magic quotes on you should stripslashes from $_POST input before mysql_real_escape_string

$value = stripslashes($value);

That should help with the matching but now with preserving backslashes in your content.
posted by missmagenta at 4:19 AM on January 26, 2012

thanks; already done stripslashes. The problem is that it's still not coping with the \6 into  bit...
posted by monkey closet at 4:25 AM on January 26, 2012

Ah, OK. Solved it myself. Waste of a question...

Nothing to do with mysql_real_escape_string - it was php itself reading \6 as . Manually escaping the backslash ("EXAMPLE_\\6") when the value is first set sorts it.
posted by monkey closet at 4:38 AM on January 26, 2012

You would never write code like this - it's not safe. Use prepared statements instead.
posted by devnull at 5:53 AM on January 26, 2012

I'm a bit confused about the "hard-coded password" vs. $_POST bit of your question (is this user input or not?) and also encountering some encoding issues in my browser, so it's hard to see what's going on in "reading \6 as .". But I'm glad you figured out your problem.

It might be a good idea, however, to code to an environment where magic_quotes are off. Since they are deprecated, it's only a matter of time before before your fix breaks (if indeed your fix is working around magic_quotes which again I'm not clear on). Ideally, your host would join the 21st century and disable them or at least give you .htaccess, but if that's not possible there's a kludge described in the manual.
posted by Dano St at 6:01 AM on January 26, 2012

As you've discovered this has nothing to do with mysql. Here's a reference for PHP string syntax.
posted by hattifattener at 10:18 AM on January 26, 2012

« Older Canadian Indian demographics   |   What is this pungent, purple flower that has... Newer »
This thread is closed to new comments.