The function adds an escape character, the backslash, \, before certain potentially dangerous characters in a string passed in to the function. The characters escaped are
\x00, \n, \r, \, ', " and \x1a.
This can help prevent SQL injection attacks which are often performed by using the ' character to append malicious code to an SQL query.
Answer from James Allardice on Stack Overflowphp - what does mysql_real_escape_string() really do? - Stack Overflow
is mysql_real_escape_string enough?
php - mysql_escape_string VS mysql_real_escape_string - Stack Overflow
mysql - How to use mysql_real_escape_string function in PHP - Stack Overflow
The function adds an escape character, the backslash, \, before certain potentially dangerous characters in a string passed in to the function. The characters escaped are
\x00, \n, \r, \, ', " and \x1a.
This can help prevent SQL injection attacks which are often performed by using the ' character to append malicious code to an SQL query.
Say you want to save the string I'm a "foobar" in the database.
Your query will look something like INSERT INTO foos (text) VALUES ("$text").
With the $text variable replaced, this will look like this:
INSERT INTO foos (text) VALUES ("I'm a "foobar"")
Now, where exactly does the string end? You may know, an SQL parser doesn't. Not only will this simply break this query, it can also be abused to inject SQL commands you didn't intend.
mysql_real_escape_string makes sure such ambiguities do not occur by escaping characters which have special meaning to an SQL parser:
mysql_real_escape_string($text) => I\'m a \"foobar\"
This becomes:
INSERT INTO foos (text) VALUES ("I\'m a \"foobar\"")
This makes the statement unambiguous and safe. The \ signals that the following character is not to be taken by its special meaning as string terminator. There are a few such characters that mysql_real_escape_string takes care of.
Escaping is a pretty universal thing in programming languages BTW, all along the same lines. If you want to type the above sentence literally in PHP, you need to escape it as well for the same reasons:
$text = 'I\'m a "foobar"';
// or
$text = "I'm a \"foobar\"";
I'm still new to PHP and as part of my self education I'm hand-coding a CMS. So far all I've managed to make it do is dynamically pull page data. What content gets displayed depends on the value given in a $_GET variable. If one isn't present, it defaults to the homepage. That took a while to figure out...so many errors...
But anyway, I realized that since the GET ends up being part of my mysql query, I should probably secure it against SQL injection. My question is if running GET through mysql_real_escape_string() is enough to do that? Is there more I should/could be doing?
Or do I even need it in this specific case? This is how the $_GET is being used in my query-
$pull_page_data = mysql_query("SELECT * FROM pages WHERE page_id = '$page'");Can havoc still be caused at the end of the query?
But back to the primary question, is doing this enough to secure my database from a basic sql injection?
$page = mysql_real_escape_string($_GET['page']);
Thanks, guys!
The difference is that mysql_escape_string just treats the string as raw bytes, and adds escaping where it believes it's appropriate.
mysql_real_escape_string, on the other hand, uses the information about the character set used for the MySQL connection. This means the string is escaped while treating multi-byte characters properly; i.e., it won't insert escaping characters in the middle of a character. This is why you need a connection for mysql_real_escape_string; it's necessary in order to know how the string should be treated.
However, instead of escaping, it's a better idea to use parameterized queries from the MySQLi library; there has previously been bugs in the escaping routine, and it's possible that some could appear again. Parameterizing the query is much, much harder to mess up, so it's less likely that you can get compromised by a MySQL bug.
Well... sort of, yes. It takes the character set of the MySQL connection into account.
http://php.net/mysql_escape_string
This function is identical to
mysql_real_escape_string()except thatmysql_real_escape_string()takes a connection handler and escapes the string according to the current character set.mysql_escape_string()does not take a connection argument and does not respect the current charset setting.
use it on the actual values in your query, not the whole query string itself.
example:
$username = mysql_real_escape_string($_POST['username']);
$query = "update table set username='$username' ...";
$rs = mysql_query($query);
Rather than using the outdated mysql extension, switch to PDO. Prepared statement parameters aren't vulnerable to injection because they keep values separate from statements. Prepared statements and PDO have other advantages, including performance, ease of use and additional features. If you need a tutorial, try "Writing MySQL Scripts with PHP and PDO".
You should never use anything "to reduce the likelihood of SQL injections" in the first place. It just doesn't work this way. You are not adding some code just in case, sort of a rabbit foot. SQL injections simply must be prevented, using certain tools. It is so easy to achieve that it just should go without saying. Just never add any variable to your SQL queries - that's all. Here is how. It doesn't only prevent injections but also relieves you from that escaping mess.
That said, no extra slashes should appear in the output unless there is an error in your code. Escaping is used for the query only, it is not stored in the database. So instead of removing extra slashes you must not add them in the first place.
No, it's not safe, because what you are doing is wrong. In your code you are echoing a variable that has only been sanitized using mysqli_real_escape_string (https://www.php.net/manual/en/function.mysql-real-escape-string.php). All that function does is prepend backslashes to some characters, like the single quote, the new line character, etc. This function was only meant to sanitize a string before using it in an SQL statement. By the way, today it is considered bad practice to use such a function, and the recommended way to make queries to the database is to use prepared statements. It's a totally different way to make queries, and you will need to use another set of PHP functions and objects.
To echo something on an HTML web page you can't use mysqli_real_escape_string for sanitization, because the set of dangerous characters is different. In HTML, you need to escape the < and > characters, for example. Other characters might have to be escaped depending on where you are echoing them, for example the single or double quote. Also, the escaping method is different from the one used for SQL: a single quote in HTML won't be prepended with a backslash when escaped, but will need to be replaced with an HTML entity, becoming '. A PHP function you might use for this is htmlspecialchars (https://www.php.net/manual/en/function.htmlspecialchars.php).
NONE.
If the first example you're doing mysql_real_escape_string() on an undefined variable.
In the second example you forgot the triling ) for the mysql_real_escape_string() function.
Correct:
<?php
$user = mysql_real_escape_string($_GET['user']);
$hash = mysql_real_escape_string($_GET['hash']);
If you really, really want to override your $_GET superglobal, then the first could be correct. But I'd guess you don't and you want the second one, although you might want to fix the missing bracket.
The main shortcoming of mysql_real_escape_string, or of the mysql_ extension in general, is that it is harder to apply correctly than other, more modern APIs, especially prepared statements. mysql_real_escape_string is supposed to be used in exactly one case: escaping text content that is used as a value in an SQL statement between quotes. E.g.:
$value = mysql_real_escape_string($value, $link);
$sql = "... `foo` = '$value' ...";
^^^^^^
mysql_real_escape_string makes sure that the $value in the above context does not mess up the SQL syntax. It does not work as you may think here:
$sql = "... `foo` = $value ...";
or here:
$sql = "... `$value` ...";
or here:
$sql = mysql_real_escape_string("... `foo` = '$value' ...");
If applied to values which are used in any context other than a quoted string in an SQL statement, it is misapplied and may or may not mess up the resulting syntax and/or allow somebody to submit values which may enable SQL injection attacks. The use case of mysql_real_escape_string is very narrow, but is seldom correctly understood.
Another way to get yourself into hot water using mysql_real_escape_string is when you set the database connection encoding using the wrong method. You should do this:
mysql_set_charset('utf8', $link);
You can also do this though:
mysql_query("SET NAMES 'utf8'", $link);
The problem is that the latter bypasses the mysql_ API, which still thinks you're talking to the database using latin1 (or something else). When using mysql_real_escape_string now, it will assume the wrong character encoding and escape strings differently than the database will interpret them later. By running the SET NAMES query, you have created a rift between how the mysql_ client API is treating strings and how the database will interpret these strings. This can be used for injection attacks in certain multibyte string situations.
There are no fundamental injection vulnerabilities in mysql_real_escape_string that I am aware of if it is applied correctly. Again though, the main problem is that it is terrifyingly easy to apply it incorrectly, which opens up vulnerabilities.
Ok, so apart from mysql_* being deprecated, I understand your wanting to know about any possible workaround that might exist. perhaps this blog post and the slides might reveal some of them.
But as this older question here shows, casting and quoting isn't full proof. There's just So many things that can wrong, and Murphy's law, twined with that ever valid mantra "Never trust the network", will go horribly wrong.
Perhaps this article, but most importantly, the follow-up to that article can reveal even more security issues. To be honest, I know mysql_real_escape_string isn't fullproof, even in combination with type casting and string formats:
printf('WHERE id = \'%d\'',(int)mysql_real_escape_string($_REQUEST['id']));
doesn't cover every possible attack.
I'm no expert on this matter, but what I can tell you is sanitizing every input, will, if anything, give you a FALSE sense of security. Most of the time, you'll know (initially) what and why and how you protect against the attacks, but your colleagues might not. They might forget something, and your entire system is compromized.
In summary: Yes, you might be able to prevent any form of malicious input from getting to your DB, but every additional action it requires is an added risk. In that scenario, the greatest liability (as always) is the developer that hasn't had is fourth cup of coffee on a monday morning. No code, no matter how defensive and well thought out, can protect itself from the monster that is a tired developer with a bad temper, going cold turkey on caffeine and nicotine.