7

Possible Duplicate:
What does mysql_real_escape_string() do that addslashes() doesn't?

If you are trying to prevent sql injection, the first thing you would do is use mysql_real_escape_string. Is it possible to inject a database using addslashes()?

Community
  • 1
  • 1
blake305
  • 2,196
  • 3
  • 23
  • 52

3 Answers3

6

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.

Marc B
  • 356,200
  • 43
  • 426
  • 500
  • but on the other hand, you can't use removeslashes with mysql_real_escape_String, can you? I have had a few times where I need to remove slashes from a database entry – blake305 Jan 19 '11 at 02:17
  • 1
    If things got stored escaped, then you've got a logic bug somewhere. But no, removeslashes will most likely, but is not guaranteed to, undo the "real escape string". It might work in simple testing, but will most likely burn you later. – Marc B Jan 19 '11 at 02:18
1

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.

viraptor
  • 33,322
  • 10
  • 107
  • 191
0

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
kos
  • 478
  • 2
  • 10