Addslashes seems to be a bit confused. Given the following 2 lines of code
$name = "Dave's test";
$newName = addslashes($name);
I am expecting $newName to be "Dave\'s test" (my one single quote nicely escaped)
However, what I'm getting is "Dave\\'s test" (note the DOUBLE backslashes). This contradicts every bit of online documentation I can find on addslashes - and causing me a lot of grief.
I am dumping the before and after addslashes results to the http error log via error_log...
error_log("before=$name after=$newName");
results...
before=Dave's test after=Dave\\'s test
Note - this is part of an ajax process, so I can't really 'echo' the results.
Any insights into why addslashes would be double up on the backslases are much appreciated.
FYI: I'm Using PHP 5.2.6 under linux with magic quotes OFF.
The special case is that if you to display a literal single-quote, escape it with a backslash(\) and if you want to display a backslash, you can escape it with another backslash(\\). Example: <? php // A Simple String echo 'I am a developer.
To output the \" sequence, you must use three backslashes. First \\ to render the backslash itself, and then \" to render the double quote. The sequence \' is rendered exactly as specified. The \ is known as an escape character.
Definition and Usage The addslashes() function returns a string with backslashes in front of predefined characters. The predefined characters are: single quote (')
The stripslashes() function removes backslashes added by the addslashes() function. Tip: This function can be used to clean up data retrieved from a database or from an HTML form.
Looks like error_log is calling addslashes internally. After reading the questions posted in reponse to my original question, I created a very trivial script...
<?php
$name = "Dave's test";
$newName = addslashes($name);
echo "name=$name. newName=$newName";
error_log("name=$name. newName=$newName");
?>
Result from the echo:
name=Dave's test. newName=Dave\'s test
Result from the error_log:
name=Dave's test. newName=Dave\\'s test
Many thanks to all who took the time to read and comment on this question. This was my first question on Stack Overflow and I was just blown away by the speed of the responses. What a great community!
For starters, why are you escaping with addslashes()
? It's an insufficient method at best, especially if you're trying to guard against SQL injection.
What else can you tell us about your configuration so we can try and replicate?
You can set magic_quotes_gpc to Off in your php.ini file. That will stop your double escaping. Remember to do this with caution as if you are using SQL in anyway you're opening yourself up to some easy SQL injections.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With