Reputation:
The user input is expected to be one of several certain strings.
Instead of using a regular expression to validate user input, would it be okay to compare the input to the strings using an if()
or switch()
statement?
Usually I would do something like
$type = preg_replace('/[^\w\s\d]/', '', trim($_GET['type']));
But would it be okay to do
switch ($_GET['type']) {
case 'test': ...code...; break;
...more cases....
default: exit;
}
So if the user input is none of the expressions allowed it exits.
Or is $_GET['type']
maybe evaluated in the switch()
statement?
Thanks.
Upvotes: 0
Views: 67
Reputation: 41820
I usually use in_array
to validate input against a list of specific acceptable values.
if (!in_array($_GET['type'], $array_of_acceptable_values, true)) {
// handle the error condition with exit; or whatever you decide to do
}
This has a couple of advantages over hard-coding the acceptable values in a control structure, in my opinion.
Upvotes: 0