2

My site uses PHP to check if the value submitted by the user using the "get" method is a certain integer. The code is something along the lines of

if ($_GET['input']==2) { ... }

However I have recently discovered that if the user inputs something like 2a, 2two or even 2omdodonsos, it is still perceived as the value 2 by PHP. However if the user inputs 23eee, 23twenty or 23ofnofnonf, it is not perceived as 2. Why does this happen? Will using this code:

 if ($_GET['input']="2") { ... }

solve the problem?

0

3 Answers 3

2

You can (and should) use input filtering to weed out the bad input:

if (is_null($input = filter_input(INPUT_GET, 'input', FILTER_VALIDATE_INT, FILTER_NULL_ON_FAILURE))) {
    // an entry that was not an integer
} elseif ($input === 2) {
    // input was 2
}

See also: filter_input()

Sign up to request clarification or add additional context in comments.

1 Comment

PHPs filter functions are underused. Shame, they're good. Upvoted.
1

For an explanation why this happens, read the documentation on type juggling.

The solution is a type safe comparison (===)

$_GET['input'] === '2'

2 Comments

Additionally, (int)sprintf('%d', $_GET['input']) could make sure you're working with a clean number. It will return 0 if the input variable couldnt be parsed into a decimal number.
@Cobra_Fast: this should be functionally equivalent to intval($_GET['input']) or (int)$_GET['input']. The sprintf is redundant. Of course it only becomes relevant as soon as the input will be used in other places than the "equals 2" check.
0

You can check if the GET value is numeric and then compare it with number 2:

if (is_numeric($_GET['input']) ) {
    switch($_GET['input']) {
      case 1:
      case 2:
       // write your code here
      break;
      default:
       //Default option
     }
 }

OR use directly === comparison operator as @fab suggested.

http://php.net/manual/en/language.operators.comparison.php

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.