The mysql use of addslashes() [duplicate]
Possible Duplicate:
What does mysql_real_escape_string() do that addslashes() doesn't?
If you are trying to prevent sql injection, the first th开发者_如何学Going you would do is use mysql_real_escape_string. Is it possible to inject a database using addslashes()?
addslashes is the rough equivalent of str_replace($str, "'", "\\'")
. You can bypass it trivially with any number of unicode sequences that evaluate down to '
in mysql, but look completely different to addslashes()
.
Mysql_real_escape_String()
on the other hand, uses the actual internal mysql escaping function, which knows exactly what to look for and fix to make it "safe" for mysql. What works for mysql may not work for another database, as each has slightly different escaping semantics and requirements, but if you're working with mysql, then the "real escape string" is the way to go.
This is what happens when you only add slashes in a language which understands unicode encodings (or mix up encodings while sending the query): http://bugs.mysql.com/bug.php?id=22243
Basically it's safer to know what the database expects in term of encoding - this way you won't end up escaping half of the character by accident, or leaving later part of a character unescaped.
And still it's possible if you add unquoted data to a table, i.e.
SELECT * FROM tbl WHERE id = 10
Here you want to make sure that this id is exactly a digit
$id = intval( $_GET[ 'id' ] ) ;
$query = "SELECT * FROM tbl WHERE id = {$id}" ;
$result = mysql_query( $query ) ;
// ... bla-bla
精彩评论