Earlier today a question was asked regarding input validation strategies in web apps.
The top answer, at time of writing, suggests in PHP
just using
I would definitely agree with the above posts, but I have one small thing to add in reply to Cheekysoft's answer, specifically:
When it comes to database queries, always try and use prepared parameterised queries. The mysqli and PDO libraries support this. This is infinitely safer than using escaping functions such as mysql_real_escape_string.
Yes, mysql_real_escape_string is effectively just a string escaping function. It is not a magic bullet. All it will do is escape dangerous characters in order that they can be safe to use in a single query string. However, if you do not sanitise your inputs beforehand, then you will be vulnerable to certain attack vectors.
Imagine the following SQL:
$result = "SELECT fields FROM table WHERE id = ".mysql_real_escape_string($_POST['id']);
You should be able to see that this is vulnerable to exploit. Imagine the id parameter contained the common attack vector:
1 OR 1=1
There's no risky chars in there to encode, so it will pass straight through the escaping filter. Leaving us:
SELECT fields FROM table WHERE id = 1 OR 1=1
I coded up a quick little function that I put in my database class that will strip out anything that isnt a number. It uses preg_replace, so there is prob a bit more optimized function, but it works in a pinch...
function Numbers($input) {
$input = preg_replace("/[^0-9]/","", $input);
if($input == '') $input = 0;
return $input;
}
So instead of using
$result = "SELECT fields FROM table WHERE id = ".mysqlrealescapestring("1 OR 1=1");
I would use
$result = "SELECT fields FROM table WHERE id = ".Numbers("1 OR 1=1");
and it would safely run the query
SELECT fields FROM table WHERE id = 111
Sure, that just stopped it from displaying the correct row, but I dont think that is a big issue for whoever is trying to inject sql into your site ;)