php
PHP:
$SQL = "SELECT goodies FROM stash WHERE secret='" . str_replace("'",'',$_POST['secret']) . "'";
Could an evil genius hacker inject SQL into my SELECT - How ?
I've had a think about this for a while and I can't see any way to inject SQL into this statement.
An SQL string that starts with a single quotes terminates at the next single quote unless it is escaped with a backslash or another quote ( '
or ''
). Since you are removing all single quotes there cannot be a doubled quote. If you escape the closing quote you will get an error, but no SQL injection.
However this method has a number of drawbacks:
For example:
$SQL = "SELECT goodies FROM stash WHERE secret='" .
str_replace("'",'',$_POST['secret']) .
"' AND secret2 = '" .
str_replace("'",'',$_POST['secret2']) .
"'";
When called with parameters and
OR 1 = 1 --
would result in:
SELECT goodies FROM stash WHERE secret='' AND secret2=' OR 1 = 1 -- '
Which MySQL would see as something like this:
SELECT goodies FROM stash WHERE secret='...' OR 1 = 1
Even if it's impossible to cause an injection in this case the drawbacks make this unsuitable for a general purpose way to avoid SQL injection.
The solution, as already pointed out, is to use a prepared statement. This is the most reliable way to prevent SQL injection attacks.
Why won't you use mysql_real_escape_string() or even better - prepared statements? Your solution seems silly.
May be. The best way is:
$query = sprintf("SELECT goodies FROM stash WHERE secret='%s'",
addcslashes(mysql_real_escape_string($_POST['secret']),'%_'));
链接地址: http://www.djcxy.com/p/93686.html
上一篇: 防止SQL注入
下一篇: PHP