I use mysql_real_escape_string() before interting information in the database, but when I want to show the data from the database, ' is replaced with \'.
So how can I get rid of that backslash? Is there a function that reverses mysql_real_escape_string()?
There is NO [built-in] function to reverse mysql_real_escape_string.
If you have only quotes but not linebreaks escaped - it is not mysql_real_escape_string to blame.
Instead of stripping, you apparently have to make your code not to add them.
There are 2 possible reasons for the slashes to appear:
magic_quotes_gpc is turned on. Just turn it off.
some extra-wise-data-sanitize function in charge. Get rid of it.
Just to make sure: not whatever "information" but only strings (query parts enclosed in quotes) have to be escaped. For the any other query part escaping is useless and you have to find another way to protect them from SQL injection
You should off the magic_quotes although mysql_real_escape_string does not add any backslash in the database that it is used just to escape the string.
However you can use the stripslashes() to remove them but the more elegant solution is to off the magic_quotes
Related
I'm running this exact query from PHP:
UPDATE commentedText SET title='ยง2.', content='<div class=\"pageParagraph\"><p>Test</p>\n</div>', last_changed='1430422172', image_banner_url='', active='', comments='[{"from":"0","to":"0","id":"1","CommentedText":"","comment":"New test with \"test\" :d"}]' WHERE id='5541d52beb2ea' AND appId='MyAppID' LIMIT 1
However when I read the row that was updated (either via PHP or MySQL Workbench), the slashes are gone. See for example
<div class=\"pageParagraph\"[..]
which is saved to the table as
<div class="pageParagraph"[..]
How come the slashes disappear?
They are disappearing before they even get to MySQL -- PHP is seeing the backslash as an escape for the double quote.
"\""
creates a string "
To keep the backslash use
"\\\""
The first escapes the second, and the third escapes the quote.
Mysql also uses backslash escapes for strings. So to use it in a query, you need to have it escaped yet again.
"\\\\\""
PHP's string will be \\"
Which in MySQL will create a string \"
Use proper escaping when dealing with queries. Applying things like addslashes() are easily defeated.
Depending on your library, mysql_real_escape_string(), mysqli_real_escape_string(), or best yet, prepared statements.
These methods of escaping will not modify the original data, so you don't have to worry about removing the escaping characters on render.
Okay, so say I have some user input that selects something from a mysql database.
I want to be safe from mysql injection so in order to do so I'd use the mysql_real_escape_string() function. But after that, I want the quote or whatever is bad from my string out of the variable completely.
EXAMPLE- :
my title variable = Herp'
escape with mysql_real_escape_string()....
then my variable = Herp\'
Now, I want the bad quote out of there. So, I want to remove the backslash & character after the backslash.. so it looks like 'Herp'.
How would I do that?
sorry if that's confusing.
If you just want to filter out quotes instead of escaping them, simply try
$myTitleVar = str_replace(array("'", '"'), '', $myTitleVar);
Before inserting it into the DB, I'd still recommend running it through mysql_real_escape_string() or even better, use PDO and parameter binding.
use stripslashes
but I would dig why that is happening. Check your magic quotes settings. For safety reasons is it good to have then set to off
When I add a comment using the variable below, apostrophes are printed with a backslash in front of them. How can I get rid of the backslashes?
Thanks in advance,
John
Example of printed result:
My roommate\'s brother\'s ex-girlfriend\'s aunt drive a Toyota.
$comment = mysql_real_escape_string($_POST['comment']);
mysql_real_escape_string() is adding backslashes, so you can inject your string safely into an SQL query -- this is acting as a protection against SQL Injections.
But this function should only be used when you want to build an SQL query -- not when you want to output something.
When you want to output a string to an HTML page, you'll generally use htmlspecialchars or htmlentities, to prevent XSS.
If you already have some backslashes before calling mysql_real_escape_string(), it might be because of Magic Quotes -- if so, you might want to first call stripslashes() on the input you get from the user, to not duplicate the backslashes.
from http://php.net/manual/en/function.mysql-real-escape-string.php
Note: If magic_quotes_gpc is enabled, first apply stripslashes() to the data. Using this function on data which has already been escaped will escape the data twice.
Isn't that exactly what mysql_real_escape_string is supposed to do? If you're still seeing the slashes after inserting the data into the database and fetching it back, make sure the magic_quotes_gpc server option is turned off.
I got this from for a login form tutorial:
function sanitize($securitystring) {
$securitystring = #trim($str);
if(get_magic_quotes_gpc()) {
$securitystring = stripslashes($str);
}
return mysql_real_escape_string($securitystring);
}
Could some one explain exactly what this does? I know that the 'clean' var is called up afterwards to sanitize the fields; I.e. $email = sanitize($_POST['email']);
Basically, if you have magic quotes switched on, special characters in POST/SESSION data will automatically be escaped (same as applying addslashes() to the string). The MySQL escape functions are better than PHP's addslashes() (although I can't remember the exact reasons why).
What your code does is check if the php.ini file has magic quotes turned on, if so the slashes are stripped from the data and then it is re-sanitised using the MySQL function. If magic quotes is not on, there is no need to strip slashes so the data is just sanitised with the MySQL function and returned.
First of all, this code is wrong.
It has wrong meaning and wrong name.
No SQL data preparation code does any cleaning or sanitization.
It does merely escaping. And this escaping must be unconditional.
and escaping shouldn't be mixed with anything else.
So, it must be three separated functions, not one.
Getting rid of magic quotes. Must be done separately at the data input.
trim if you wish. It's just text beautifier, no critical function it does.
mysql_real_escape_string() to prepare data for the SQL query.
So, the only mysql related function here is mysql_real_escape_string(). Though it makes no data "clean", but merely escape delimiters. Therefore, this function must be used only with data what considered as a string and enclosed in quotes. So, this is a good example:
$num=6;
$string='name';
$num=mysql_real_escape_string($num);
$string=mysql_real_escape_string($string);
$query="SELECT * FROM table WHERE name='$name' AND num='$num'";
while this example is wrong:
$num=6;
$string='name';
$num=mysql_real_escape_string($num);
$string=mysql_real_escape_string($string);
$query2="SELECT * FROM table WHERE name='$name' AND num=$num";
Even though $query2 would not throw a syntax error, this is wrong data preparation and mysql_real_escape_string would help nothing here. So, this function can be used only to escape data that treated as a string. though it can be done to any data type, there is some exceptions, such as LIMIT parameters, which cannot be treat as a strings.
trim() gets rid of all whitespace, and if magic quotes is on, the backslash is removed from any escaped quotes with stripslashes(). mysql_real_escape_string() readies a string to be used in a mysql query safely.
here are the docs for the functions used: http://php.net/manual/en/function.trim.php, http://php.net/manual/en/function.get-magic-quotes-gpc.php, http://php.net/manual/en/function.stripslashes.php, http://php.net/manual/en/function.mysql-real-escape-string.php
mysql_real_escape_string is used to escape characters in the string to add backslashes to characters such as ', which prevents an attacker from embedding additional SQL statements into the string. If the string is not escaped, additional SQL can be appended. For example, something along the lines of this might be executed:
SELECT * FROM tbl WHERE col = 'test' ; DELETE * FROM tbl ; SELECT 'owned'
magic_quotes does escaping of its own, although if I remember correctly its use is now discouraged. Besides, the MySQL function will do all the escaping you need to prevent SQL injection attacks.
Some (old) servers have magic_quotes enabled. That means that all external input is altered to (supposedly) escape it in order to be injected in a MySQL query. So O'Brian becomes O\'Brian. This was an early design decision by the PHP team that proved wrong:
You don't always need to inject input into database queries
Not all DB engines use back slashes as escape char
Escaping single quotes with backs slashes is not enough, even for MySQL
Your server security relies on a PHP setting that can be disabled
So it's way better to code without magic_quotes. The problem comes with redistributable code: you cannot know if the server will have magic_quotes enabled or disabled. So you can use get_magic_quotes_gpc() to detect it they're on and, if so, use stripslashes() to (try to) recover the original input.
I'm totally aware of the aberration of Magic Quotes in PHP, how it is evil and I avoid them like pest, but what are magic_quotes_runtime? From php.ini:
Magic quotes for runtime-generated
data, e.g. data from SQL, from exec(),
etc.
Is is something I should check if ON and turn OFF with:
set_magic_quotes_runtime(false);
Is it often ON by default? I know it's deprecated in 5.3.0 and removed in 6.0.0 but since my script support 5.1.0+ I would like to know how to handle this in "legacy" PHP (if it's relevant).
Edit: To make things clear I want to exit('Turn OFF Magic Quotes'); when Magic quotes are ON. I'm not relying on them!
If magic_quotes_runtime is enabled, most functions that return data from any sort of external source including databases and text files will have quotes escaped with a backslash. If magic_quotes_sybase is also on, a single-quote is escaped with a single-quote instead of a backslash.
http://www.php.net/manual/en/info.configuration.php#ini.magic-quotes-runtime
If magic quotes are ON, php will automatically escape quotes coming in POST or GET variables and automatically un-escape them when pulling data out of a database for example.
If you use things like addslashes(), mysql_escape_string() or mysql_real_escape_string() with magic quotes on, you'll end up double-escaping quotes.
The reason it's evil is the same reason addslashes() and mysql_escape_string() are evil - because it doesn't capture every possible method of putting a quote in a string. It gives you a false sense of security in thinking that you don't have to worry about escaping quotes anymore when in reality you still do.
Also, as if escaping strings wasn't enough of a PITA already, now you have to check if magic quotes are on or off before you try to escape or un-escape a string to avoid double escaping.
You could use ini_get to check for it's value, like this:
ini_get('magic_quotes_runtime');
Also you should wrap calls to set_magic_quotes_runtime/get_magic_quotes_runtime in function_exists calls, like that:
if (function_exists('set_magic_quotes_runtime')) {
set_magic_quotes_runtime(true/false);
}
But of course, one should not rely on magic quotes at all and should have them disabled if possible. Se this link for a coule of reasons why: http://www.php.net/manual/en/security.magicquotes.whynot.php