Tutorial :is_int() cannot check $_GET in PHP?


Here is my code:

<?php  $id = $_GET["id"];    if (is_int($id) === FALSE)  {      header('HTTP/1.1 404 Not Found');      exit('404, page not found');      }  ?>  

It always enters inside the if.


is_int checks that the data type is an integer, but everything in $_GET will be a string. Therefore, it will always return false.

In a pinch, you could cast to an integer and then check for != 0.

$id = isset($_GET['id']) ? (int) $_GET['id'] : null;    if (!$id) { // === 0 || === null    header('HTTP/1.1 404 Not Found');    exit('404, page not found');  }  

But a more robust solution would involve some type of input string validation / filtering, like PHP's built-in filter_input_array().

(Edited post on Oct/13 since it is still receiving upvotes and it was somewhat confusingly worded.)


User input in $_GET array (as well as the other superglobals) all take the form of strings.

is_int checks the type (i.e. string) of the value, not whether it contains integer-like values. For verification that the input is an integer string, I would suggest either something like ctype_digit or an integer filter (FILTER_VALIDATE_INTâ€"this has the benefit of actually changing the value to type integer). Of course you could also typecast it with (int).


From the PHP documentation for is_int:

Note: To test if a variable is a number or a numeric string (such as form input, which is always a string), you must use is_numeric().


Any user input comes in as a string, because PHP has no way to tell what data type you expect the data to be.

Cast it to an integer or use a regex if you want to make sure it's an integer.

<?php  $id = $_GET["id"];    if ((int) $id == 0)  {      header('HTTP/1.1 404 Not Found');      exit('404, page not found');      }  ?>  


Try using is_numeric instead of is_int. is_numeric checks to see if it is given something that can be a number ($_GET returns strings I think). is_int checks to see if the variable is of type int


Use is_numeric() to evaluate the content and is_int() to evaluate the type.


Or, you could just use a regex match to check if the string is an integer.

if(preg_match('/^\d+$/',$_GET['id'])) {    // is an integer  }  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »