PHP is_int not working properly

I have a page (index.php) that takes a GET variable from a URL and validates it for security reasons. This GET variable should only be an integer. I use the following code to check this, but in all instances, integer or not, I get the index.php page. The title never appears. After this code, the rest of the page starts with the html tag.

PHP:

 <?php ob_start(); session_start(); $q=trim($_GET['q']); if (!is_numeric($q)){ header("HTTP/1.0 404 Not Found"); } ?> 
+6
source share
3 answers

It will not be integer if it is passed in the query string.

Try is_numeric()

+19
source

There is a better way to do this which distinguishes int:

 $q = (int) $_GET['q']; 

The is_int command behaves as expected. Because GET arguments are always strings. Try var_dumping them.

+5
source

Sometimes you want to check the input, which should be a number, but in $_GET or $_POST you get it as a string. is_numeric() can be problematic as it allows you to use hexadecimal, binary and octal format (from the manual):

Thus +0123.45e6 is a valid numeric value. Hexadecimal (eg 0xf4c3b00c), Binary (eg 0b10100111001), Octal (eg 0777) notation is allowed too but only without sign, decimal and exponential part.

You cannot use is_int() since it is only for integer values ​​(not a string!), So ... You can check numbers that are strings AND integers, this way:

 function is_int_val($value){ if( ! preg_match( '/^-?[0-9]+$/', $value ) ){ return FALSE; } /* Disallow leading 0 */ // cast value to string, to make index work $value = (string) $value; if( ( $value[0] === '-' && $value[1] == 0 ) || ( $value[0] == 0 && strlen( $value ) > 1 ) ){ return FALSE; } return TRUE; } is_int_val('33'); // true is_int_val('33a'); // false is_int_val('033'); // false 

It is also possible to override the is_int () function using override_function () , but it can be useful in the original version.

0
source

Source: https://habr.com/ru/post/906599/


All Articles