is_int() cannot check $_GET in PHP?

无人久伴 提交于 2019-12-03 14:30:29

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
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!