0

Possible Duplicate:
php validate integer

How would I generally validate a user input is an integer? I mean i receive a variable throught $_GET and this must be an integer.

Community
  • 1
  • 1
Hans
  • 41
  • 1
  • 5
  • 6
    `filter_input(INPUT_GET, $name, FILTER_VALIDATE_INT)` – Gordon Apr 15 '12 at 16:17
  • 1
    `($_GET['var'] === (string)(int) $_GET['var'])` – hakre Apr 15 '12 at 16:22
  • 1
    I think that's the controversy here, because one will never get a real integer value through a request, because it's always a string. Thats surely confusing while learning PHP – dan-lee Apr 15 '12 at 16:25

2 Answers2

2

You could use:

preg_match('/^[0-9]+$/', $_GET['variable_name']);
Songo
  • 5,433
  • 7
  • 55
  • 93
  • Would work, but is a bit overkill, don't you think? – nico Apr 15 '12 at 16:24
  • @nico well he didn't specify a certain case for him, so I think the most general solution is the most appropriate :) – Songo Apr 15 '12 at 16:25
  • how is this more general than just casting to int? – nico Apr 15 '12 at 16:27
  • @nico because the user was asking for a validation not casting the input to integer. What if the input was `hfk`? This should fail the validation. – Songo Apr 15 '12 at 16:31
  • OK, you are right, I didn't think of the fact that `"a" == (int)"a"`, I rest my case – nico Apr 15 '12 at 16:35
  • 1
    PHP has different ways how an integer can be written, some regex: `(([+-]?([1-9][0-9]*|0))|([+-]?(0[xX][0-9a-fA-F]+))|([+-]?(0[0-7]+)))` – hakre Apr 15 '12 at 16:45
  • If don't care about supportig the alternate numeric representations (e.g. hex notation), then `ctype_digit()` can be used. It will check if all the characters in a string are 0-9. It will only operate on a string, so: `ctype_digit(1) === false`, where `ctype_digit('1') === true` – kfriend Apr 28 '15 at 20:08
0

You should probable use the is_numeric() function or maybe the is_int() function if you plan on just working with integers and not other types such as floats.

gimg1
  • 1,099
  • 10
  • 23
  • 2
    is_int wont work because $_GET contains strings only. is_numeric wont work because it will allow floats. – Gordon Apr 15 '12 at 16:46
  • That is a minor problem. A simple method of getting around this would be by using a nested if to check if it is numeric first and then if it is an int. – gimg1 Apr 16 '12 at 11:25
  • 2
    which will always result in a false, because even if it is a numeric string, it is not an integer, e.g. is_numeric("123") !== is_int("123") – Gordon Apr 16 '12 at 13:03