user1834033
user1834033

Reputation:

Is it okay to validate user input by comparing it to a string?

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

Answers (1)

Don't Panic
Don't Panic

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.

  • less code
  • simpler to update the list of values if needed
  • easy to load the value list from another source (config file, etc.) if you decide to do that

Upvotes: 0

Related Questions