[英]PHP: filter_var sanitization secure enough?
I have a PHP script with the following line:我有一个包含以下行的 PHP 脚本:
$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:在这种情况下是安全的,但对于更通用的方法,我宁愿将
mysql_real_escape_string
与类型转换结合使用:
$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.在最坏的情况下,这将导致
0
并且也会逃避所有恶意输入。 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. mysql_real_escape_string
可用于各种数据以使其安全地进行查询,这使其成为所有转义/清理功能中最通用的。
Without going as far as using prepared statements, you can use sprintf to create your SQL and to handle the type casting automatically:无需使用准备好的语句,您可以使用 sprintf 来创建 SQL 并自动处理类型转换:
$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.有关语法,请参阅 PHP 手册中的sprintf条目。
It gets even simpler if you use array_map
to escape all $_GET
and $_POST
variables, then you can use them as is:如果您使用
array_map
转义所有$_GET
和$_POST
变量,它会变得更加简单,然后您可以按原样使用它们:
$_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']);
可能这对你有用......!
$query=query("SELECT * FROM products WHERE product_id= ". escape_string($_GET['id']) . " ");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.