Why use mysql_real_escape_string, doesn't adds

2019-07-05 03:16发布

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.

标签: php security
2条回答
We Are One
2楼-- · 2019-07-05 03:38

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.

查看更多
戒情不戒烟
3楼-- · 2019-07-05 03:44

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.

查看更多
登录 后发表回答