PHP:
$SQL = "SELECT goodies FROM stash WHERE secret='" . str_replace("'",'',$_POST['secret']) . "'";
Could an evil genius hacker inject SQL into my SELECT - How ?
PHP:
$SQL = "SELECT goodies FROM stash WHERE secret='" . str_replace("'",'',$_POST['secret']) . "'";
Could an evil genius hacker inject SQL into my SELECT - How ?
Why won't you use mysql_real_escape_string() or even better - prepared statements? Your solution seems silly.
Why just don't use mysql_escape_string
? And yes, he could, adding "
instead of '
and plus, this query will give you an error, I guess.
I think that is safe, however, user can not post/search any string contain '
-> not good
May be. The best way is:
$query = sprintf("SELECT goodies FROM stash WHERE secret='%s'",
addcslashes(mysql_real_escape_string($_POST['secret']),'%_'));
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.