Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validating whether $_REQUEST contents is an int

Tags:

ajax

php

I am trying to do a basic operation: to check whether string is a number.

This does not work:

$qty = $_REQUEST[qty];
if (is_int($qty) == FALSE) {
  echo "error";
} else {
  echo "ok";
}

This one does:

$qty = 1;
if (is_int($qty) == FALSE) {
  echo "error";
} else {
  echo "ok";
}

$_REQUEST[qty] is posted with AJAX request ($.post). $_REQUEST[qty] is NOT empty and contains only number (1).

is_numeric() is not going to work, since it treats 1e4 as a number.

like image 532
Alex G Avatar asked Jan 02 '12 13:01

Alex G


4 Answers

is_int will only return true if the variable is of integer type. if you are trying to test if the variable contains a string which represents a number, use:

is_numeric("1");

source: http://php.net/manual/en/function.is-int.php

EDIT:

use ctype_digit() to check for every character in the string if it's a number to rule out "1e4"

like image 178
Rodik Avatar answered Nov 14 '22 07:11

Rodik


If you want to check for the presence of digits only, you can use ctype_digit .

like image 38
Srisa Avatar answered Nov 14 '22 08:11

Srisa


try "is_numeric()" instead of "is_int"...

i think that u r getting a String from your Request... and is_int really checks wether a given object is a integer... But it isn't -> it's a String.

is_numeric just checks, wether a object is convertable into an integer. If so, it returns true, otherwise false...

$qty = $_REQUEST[qty];
if (is_numeric($qty) == FALSE) {
  echo "error";
} else {
  echo "ok";
}

PS: Use $_POST[] or $_GET[] insetead of $_REQUEST[] ;)

like image 41
jeff Avatar answered Nov 14 '22 06:11

jeff


You mention you cannot use is_numeric because it treats 1e4 as a number. Well, 1e4 is a number. Specifically 1 * 10^4.

You could use is_int(intval($_REQUEST['qty'])), but as intval always returns an int (0 on failure or empty input) you run the risk of false positives. However, combined with is_numeric or filter_var you should be on pretty solid ground.

like image 22
nikc.org Avatar answered Nov 14 '22 07:11

nikc.org