ahota ahota - 1 year ago 65
PHP Question

Checking if a variable is an integer in PHP

I have the following code

$page = $_GET['p'];

if($page == "")
$page = 1;
if(is_int($page) == false)
setcookie("error", "Invalid page.", time()+3600);
//else continue with code

which I am going to use for looking at different "pages" of a database (results 1-10, 11-20, etc). I can't seem to get the is_int() function to work correctly, however. Putting "1" into the url (noobs.php?p=1) gives me the invalid page error, as well as something like "asdf".

Answer Source

All $_GET parameters have a string datatype, therefore, is_int will always return false.

You can see this by calling var_dump:

var_dump($_GET['p']); // string(2) "54"

Using is_numeric will provide the desired result (mind you, that allows values such as: 0x24).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download