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?
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()
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.
For an explanation why this happens, read the documentation on type juggling.
The solution is a type safe comparison (===
)
$_GET['input'] === '2'