Reputation: 571
How do prevent sql injection in php but still show " and '? A the moment I am using
$input = strip_tags($input);
$input = htmlentities($input);
However the output is \" and \'. Is there anyway I can show " and ' without the slashes but keep them there so I don't get injected?
Upvotes: 1
Views: 979
Reputation: 145512
There is no magic solution for being careless.
Also those slashes alone don't prevent SQL injections. The presence of them indicates another problem, magic_quotes. Magic quotes were a convenience feature in PHP2, never intended as security function. (Well accidentially they were secure around 1997 when databases didn't support multibyte charsets).
Anyway, disable magic_quotes. Use manual escaping (mysql_real_escape_string) or better yet the much more convenient prepared statements with PDO.
If you want to be lazy, disable magic_quotes still. But use $_GET = array_map("mysql_real_escape_string", $_GET);
and do the same for $_POST and $_REQUEST at the start of your scripts and after the database connection was established.
And then apply htmlentities(stripslashes($input))
for writing output to ge rid of the extraneous backslashes.
Upvotes: 0
Reputation: 25445
First, that code is not stripping backslashes, of course they're still there. Use stripslashes() to take out backslashes, but DON'T DO IT. If you see those slashes in the DB, and you HAVE USED mysql_real_escape_string, chances are you have magic_quotes_gpc on, and you're just adding another set of slahses. Remove those auto added first and then apply mysql_real_escape_string, they won't show this way but will still be there and make for a safe use in querying your DB.
Upvotes: 1
Reputation: 449803
The method you show is not a proper way to protect against SQL injection!
Always use the sanitation method provided by the database library you are using, e.g. mysql_real_escape_string()
if you work with the standard mysql library. The sanitation method will not alter any characters in the end result.
Alternatively, use prepared statements in PDO or mysqli - those do input sanitation automatically if you bind the incoming data correctly.
Upvotes: 5
Reputation: 117364
Make use of prepared statements.
https://www.php.net/manual/en/pdostatement.bindparam.php
OR
https://www.php.net/manual/en/mysqli-stmt.bind-param.php
Upvotes: 1