Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is_int() cannot check $_GET in PHP?

Tags:

php

integer

get

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.

like image 696
ilhan Avatar asked Jun 28 '10 18:06

ilhan


People also ask

How do you check if a number is a whole number in PHP?

if y is anything other then a whole number the result is not a zero (0). A test then would be: if (y % 1 == 0) { // this is a whole number } else { // this is not a whole number } var isWhole = (y % 1 == 0? true: false); // to get a boolean return.

How do you check a variable is integer or not in PHP?

The is_int() function checks whether a variable is of type integer or not. This function returns true (1) if the variable is of type integer, otherwise it returns false.

How do you check if a value is int or not?

isInteger() method returns true if a value is an integer of the datatype Number. Otherwise it returns false .


2 Answers

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

like image 122
Matthew Avatar answered Nov 11 '22 06:11

Matthew


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

like image 22
salathe Avatar answered Nov 11 '22 04:11

salathe