开发者

PHP: filter_var sanitization secure enough?

开发者 https://www.devze.com 2022-12-15 23:26 出处:网络
I have a PHP script with the following line: 开发者_StackOverflow中文版$query = \"SELECT * FROM products WHERE product_id=\'\" . filter_var($_GET[id], FILTER_SANITIZE_NUMBER_INT) . \"\'\";

I have a PHP script with the following line:

开发者_StackOverflow中文版
$query = "SELECT * FROM products WHERE product_id='" . filter_var($_GET[id], FILTER_SANITIZE_NUMBER_INT) . "'";

Is this safe enough? How would you improve this code?


It is safe for that case, but for a more general approach, I'd rather use mysql_real_escape_string in conjunction with type casting:

$query = "SELECT * FROM products WHERE product_id='" . (int)mysql_real_escape_string($_GET['id']) . "'";

In the worst case, that will result in a 0 and will escape all malicious input also. mysql_real_escape_string can be used on all kinds of data to make it safe for queries, which makes it the most versatile of all escape/sanitation functions.

Without going as far as using prepared statements, you can use sprintf to create your SQL and to handle the type casting automatically:

$query = sprintf("SELECT * FROM products WHERE product_id = '%d'", mysql_real_escape_string($_GET['id']));

See the sprintf entry from the PHP manual for the syntax.

It gets even simpler if you use array_map to escape all $_GET and $_POST variables, then you can use them as is:

$_GET = array_map('mysql_real_escape_string', $_GET);
$_POST = array_map('mysql_real_escape_string', $_POST);

$query = sprintf("SELECT * FROM products WHERE product_id = '%d'", $_GET['id']);


I usually just use intval:

$product_id = intval($_GET['id']);
$query = "SELECT * FROM products WHERE product_id='" . $product_id . "'";


May be this works for you...!

$query=query("SELECT * FROM products WHERE product_id= ". escape_string($_GET['id']) . " ");
0

精彩评论

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