is_int() cannot check $_GET in PHP?

12,174

Solution 1

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.)

Solution 2

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).

Solution 3

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().

Solution 4

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');
    }
?>

Solution 5

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

Share:
12,174
ilhan
Author by

ilhan

https://www.buymeacoffee.com/ilhan

Updated on June 28, 2022

Comments

  • ilhan
    ilhan almost 2 years

    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.