Mysql seems to remove slashes from string - php

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.

Related

How to check a string is escaped twice or not

Is is possible to find a string is escaped twice or not using SQL Query (REGEXP) or using PHP?
Please help me on this. I tried more to find it but I'm not getting it anywhere.
$item = "Zak's Laptop";
$escaped_item = mysql_escape_string($item);
$escaped_item_twice = mysql_escape_string($escaped_item);
Here i need to find out that $escaped_item_twice is escaped twice. by their result string which is stored in db already. (i.e) i already stored some strings in db with double escape. I want to get those things and to use stripslashes() on that data. How can i get that data?
You cannot make a difference. Escaping is nothing more than adding some \s (in this case). It leaves no other trail. You cannot tell whether double escaping occurred or you simply wanted to escape an escape character (\\) that was meant to be there.

How to save HTML in database

I have some question about saving html code in mysql database
every time when I put the charter " ' " in the database it changes to " / ".
Example:
somthing like that
<p>That's my name</p>
After saving it look like this:
<p>That\'s my name</p>
what can i do?
thank u all
Use parameterized queries to escape data going into the database
Use nothing else to escape data going into the database (otherwise you will double escape which can use this problem)
Do not use mysql_real_escape_string
Do not use addslashes
etc
Do not escape data coming out of the database (since that will cause this problem)
Make sure magic quotes are disabled (since having them turned on will escape data going into and out of the database and cause this problem).
You are using addslashes like escape functions in your code.
addslashes() — Quote string with slashes - http://php.net/manual/en/function.addslashes.php
stripslashes() — Un-quotes a quoted string - http://php.net/manual/en/function.stripslashes.php
Use stripslashes to remove '\' from HTML data. Actually (') is used define string in MySql, so it ecaspe it (by putting \ in-front) in order to avoid any unintentional use.

What does it mean to escape a string?

I was reading Does $_SESSION['username'] need to be escaped before getting into an SQL query? and it said "You need to escape every string you pass to the sql query, regardless of its origin". Now I know something like this is really basic. A Google search turned up over 20, 000 results. Stackoverflow alone had 20 pages of results but no one actually explains what escaping a string is or how to do it. It is just assumed. Can you help me? I want to learn because as always I am making a web app in PHP.
I have looked at:
Inserting Escape Characters, What are all the escape characters in Java?,
Cant escape a string with addcslashes(),
Escape character,
what does mysql_real_escape_string() really do?,
How can i escape double quotes from a string in php?,
MySQL_real_escape_string not adding slashes?,
remove escape sequences from string in php I could go on but I am sure you get the point. This is not laziness.
Escaping a string means to reduce ambiguity in quotes (and other characters) used in that string. For instance, when you're defining a string, you typically surround it in either double quotes or single quotes:
"Hello World."
But what if my string had double quotes within it?
"Hello "World.""
Now I have ambiguity - the interpreter doesn't know where my string ends. If I want to keep my double quotes, I have a couple options. I could use single quotes around my string:
'Hello "World."'
Or I can escape my quotes:
"Hello \"World.\""
Any quote that is preceded by a slash is escaped, and understood to be part of the value of the string.
When it comes to queries, MySQL has certain keywords it watches for that we cannot use in our queries without causing some confusion. Suppose we had a table of values where a column was named "Select", and we wanted to select that:
SELECT select FROM myTable
We've now introduced some ambiguity into our query. Within our query, we can reduce that ambiguity by using back-ticks:
SELECT `select` FROM myTable
This removes the confusion we've introduced by using poor judgment in selecting field names.
A lot of this can be handled for you by simply passing your values through mysql_real_escape_string(). In the example below you can see that we're passing user-submitted data through this function to ensure it won't cause any problems for our query:
// Query
$query = sprintf("SELECT * FROM users WHERE user='%s' AND password='%s'",
mysql_real_escape_string($user),
mysql_real_escape_string($password));
Other methods exist for escaping strings, such as add_slashes, addcslashes, quotemeta, and more, though you'll find that when the goal is to run a safe query, by and large developers prefer mysql_real_escape_string or pg_escape_string (in the context of PostgreSQL.
Some characters have special meaning to the SQL database you are using. When these characters are being used in a query they can cause unexpected and/or unintended behavior including allowing an attacker to compromise your database. To prevent these characters from affecting a query in this way they need to be escaped, or to say it a different way, the database needs to be told to not treat them as special characters in this query.
In the case of mysql_real_escape_string() it escapes \x00, \n, \r,\, ', " and \x1a as these, when not escaped, can cause the previously mentioned problems which includes SQL injections with a MySQL database.
For simplicity, you could basically imagine the backslash "\" to be a command to the interpreter during runtime.
For e.g. while interpreting this statement:
$txt = "Hello world!";
during the lexical analysis phase ( or when splitting up the statement into individual tokens) these would be the tokens identified
$, txt, =, ", Hello world!, ", and ;
However the backslash within the string will cause an extra set of tokens and is interpreted as a command to do something with the character that immediately follows it :
for e.g.
$txt = "this \" is escaped";
results in the following tokens:
$, txt, =, ", this, \, ", is escaped, ", and ;
the interpreter already knows (or has preset routes it can take) what to do based on the character that succeeds the \ token. So in the case of " it proceeds to treat it as a character and not as the end-of-string command.

Explanation of this SQL sanitization code

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.

The counterpart of mysqli::real_escape_string?

stripslashes() ? That's lame and so 4.0. What's the 5.0 counterpart of mysqli::real_escape_string that strips all slashes added for SQL queries?
Got some other questions:
Tried to update a record and added a single quote in a text field, turns out phpMyAdmin escapes the string with single quotes instead of slashes - e.g. a single quote is escaped as '' (2 single quotes) instead of \' - what function is phpMyAdmin using or is it its own? So, mysql supports 2 approaches for escaping strings, namely slash and single quote?
Do I always have to unslash the string selected from mysql? Cause' you know it's slashed at insertion. But I thought I don't have to.
Any ideas, thanks!
If you don't want to go with PDO, and you are using mysqli, you should be using prepared statements, so you don't have to worry about escaping quotes with things like mysql_real_escape_string_i_mean_it_this_time.
More specifically, you can call mysqli->prepare to prepare your query. Call mysqli_stmt->bind_param to set the parameter values. And, call mysqli_stmt->execute to execute the query.
Use PDO instead of any of the mysql[i]/pgsql/... extensions.
If you're just looking to reverse the damage done by magic quotes, though, stripslashes() is exactly what you're looking for.
ini_set('magic_quotes_runtime', false);

Categories