开发者

How can i prevent sql injection but keep " and '?

开发者 https://www.devze.com 2023-02-08 16:54 出处:网络
How do prevent sql injection in php but still show \" and \'? A the moment I am using $input = strip_tags($input);

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 anyw开发者_如何学Pythonay I can show " and ' without the slashes but keep them there so I don't get injected?


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.


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.


Make use of prepared statements.
http://de2.php.net/manual/en/pdostatement.bindparam.php
OR
http://de2.php.net/manual/en/mysqli-stmt.bind-param.php


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消