Going trough some PHP code I have to clean up I’m a bit surprised at finding that it can take many lines using everything from preg_match to addslashes and mysql_escape_string to sanitize numeric input.
So I thought I share a method that I find handy:
$id = (int) $_GET["id"];
In some cases it might want to handle any attempts to input a string where an number is expected though.
When converting a string to an integer PHP will default to 0, rather than something handy like NaN.
Usually it’s not too much a problem if someone tries to hack you site and only gets directed to the contents for “id=0″ when they try to input “id=1;DROP TABLE users”.
But one would think that this should work as a check:
$id = (int) $_GET["id"];
if($_GET["id"] == $id){
echo "ok";
} else {
die("error");
}
But even if $_GET["id"] is “foo” it will equal 0, again because PHP will evaluate a string that doesn’t represent a number as 0.
Instead I use this to check if the input string actually evaluates to a number:
if(ctype_digit(strval($_GET["id"]))){
echo "ok";
} else {
die("error");
}
Related posts:
Since you want a numeric answer, and string computes as 0, why can’t you verify a numeric input by $numeric_input = $_GET['number']*(some integer)/(the same integer)?
I’ve tested it, and it seems to clean any string and leave the result blank if the answer wasn’t a number. I’m very open to correction if you can show me the weakness of this method.
Thanks.