May 102008
 

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");
}
Share/Bookmark

Switch to our mobile site