I have a PHP script with the following line:
$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?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
It is safe for that case, but for a more general approach, I’d rather use
mysql_real_escape_stringin conjunction with type casting:In the worst case, that will result in a
0and will escape all malicious input also.mysql_real_escape_stringcan 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:
See the sprintf entry from the PHP manual for the syntax.
It gets even simpler if you use
array_mapto escape all$_GETand$_POSTvariables, then you can use them as is: