tags:

views:

87

answers:

2

I was looking through the docs and stumbled onto mysql_real_escape_string() and I'm not understanding why it's useful when you can just addslashes(). Can someone show me a scenario as to why it's useful?

I'm also curious why it requires a database connection.... that seems like a lot of overhead.

+7  A: 

There is a great article about this here. And this discussion also points out the pros and cons of each solution.

addslashes() was from the developers of PHP whereas mysql_real_escape_string uses the underlying MySQL C++ API (i.e. from the developers of MySQL). mysql_real_escape_string escapes EOF chars, quotes, backslashes, carriage returns, nulls, and line feeds. There is also the charset aspect.

m_oLogin
+1 for the link to Shiflett's site, just what I would have posted.
Grant Palin
-1 That "great article" is very old and that has been patched. Try it for your self.
Rook
+1  A: 

Nether mysql_real_escape_string() or addslashes() prevent everything (what about xss or even xsrf?), and most importantly nether of them prevent all SQL Injection.

For instance this code is vulnerable to sql injection:

mysql_query("select * from user where id=".mysql_real_escape_string($_GET[id]));

Exploit:

http://localhost/test.php?id=1 or sleep(50)

patch:

mysql_query("select * from user where id='".mysql_real_escape_string($_GET[id])."'");

Use parametrized queries with either ADODB or PDO, this is the only bullet proof sql injection protection.

Rook
What do you mean ADODB or PDO ?
Webnet
@Webnet they are php libraries http://adodb.sourceforge.net/
Rook