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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With