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 goes inside if.

+7
php integer get
source share
7 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 .

As a last resort, you can apply 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 reliable solution will include some type of input string checking / filtering, for example, the built-in PHP filter_input_array() .

(The edited post is in Oct / 13, as it still receives upvotes, and this was somewhat vaguely worded.)

+31
source share

Entering the user into the $ _GET array (like other superglobals) takes the form of strings.

is_int checks the type (i.e. string ) of the value, and whether it contains integer values. To verify that the input is an entire string, I would suggest either something like ctype_digit or an integer filter ( FILTER_VALIDATE_INT - it makes sense to actually change the value to enter an integer). Of course, you could also specify it with (int) .

+5
source share

From the PHP documentation for is_int:

Note. To check if a variable is a number or a numeric string (for example, a form input, which is always a string), you should use is_numeric () .

+3
source share

Any user input comes as a string because PHP cannot tell what type of data you expect from the data.

Pass it to an integer or use a regular expression if you want to make sure it is an integer.

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

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

+1
source share

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

0
source share

Or you can just use regex to check if a string is an integer.

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

All Articles