Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php validate integer

Tags:

I`m wonder why this not working

    echo gettype($_GET['id']); //returns string
  if(is_int($_GET['id']))
  {
   echo 'Integer';
  }

How to validate data passing from GET/POST if it is integer ?

like image 692
omtr Avatar asked Nov 04 '10 18:11

omtr


People also ask

Is integer validation in PHP?

The FILTER_VALIDATE_INT filter is used to validate value as integer. FILTER_VALIDATE_INT also allows us to specify a range for the integer variable. Possible options and flags: min_range - specifies the minimum integer value.

How do you check if an input is a number in PHP?

The is_numeric() function checks whether a variable is a number or a numeric string. This function returns true (1) if the variable is a number or a numeric string, otherwise it returns false/nothing.

Can PHP be used for validation?

PHP validates the data at the server-side, which is submitted by HTML form. You need to validate a few things: Empty String. Validate String.

What is Filter_var function in PHP?

The filter_var() function filters a variable with the specified filter. This function is used to both validate and sanitize the data. Syntax :- filter_var(var, filtername, options)


2 Answers

Can use

$validatedValue = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT);

See http://php.net/filter_input and related functions.

like image 86
Gordon Avatar answered Sep 18 '22 14:09

Gordon


The manual says:

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

Alternative you can use the regex based test as:

if(preg_match('/^\d+$/',$_GET['id'])) {
  // valid input.
} else {
  // invalid input.
}
like image 22
codaddict Avatar answered Sep 20 '22 14:09

codaddict