1

There are are a few finite values that my variable $_GET['action'] can take, either "new", "edit", or "delete".

I want to sanitize my input for security and make sure the variable is only one of those above values, how can I do that using regular expressions?

I don't want to go and say:

if(isset($_GET['action']) && ($_GET['action'] == 'new' || $_GET['action'] == 'edit' || $_GET['action'] == 'delete'))
1
  • I recommend to make a function of it. This way you are more flexible. Commented May 19, 2013 at 14:22

6 Answers 6

5

I would not use a regex for this. Use in_array() to check a value against a white list:

if(!in_array($_GET, array("new", "edit", "delete"), TRUE)) {
    die('Error!');
}
Sign up to request clarification or add additional context in comments.

5 Comments

why? would regex be slower?
I expect a regex is much slower. Will test, give me a minute
Is the strict flag necessary?
@kingkero Good question! :) In this special case: not. However, I suggested it in the example, as the real data might be sensitive for it
@user961627 My little test showed me that in_array() is ~ 30% faster then preg_match()
2

A switch is probably the best solution, but seeing nothing of your code makes it hard to tell. The regex you are searching for looks like the following

/^(new|edit|delete)$/i

Described in words it checks if between the beginning and the end of the line there is one of the three possibilities (case insensitive)

1 Comment

agree with this, regex should be more of a pattern recongition than a simple value checker
2

It's simple just do:

if( isset($_GET['action']) && preg_match("/^(new|edit|delete)$/i", $_GET['action']))
     doSomething();

Comments

1

this should help

if(isset($_GET['action']) && in_array($_GET['action'], array('new', 'edit', 'delete')))

or

$allowed_methods = array('new', 'edit', 'delete');
if(isset($_GET['action']) && in_array($_GET['action'], $allowed_methods))

Comments

1

Match them using the or (|) operator

if (preg_match("/^(new|edit|delete)$/", $_GET['action'])) { ...

Comments

1
if(isset($_GET['action'])){
  switch($_GET['action']){
    case 'edit':
        //etc...
        break;
    case 'new':
        //etc...
        break;
    case 'delete':
        //etc...
        break;
    default:
        echo 'No valid actions';
  }
}

Use the switch for a good action management

2 Comments

Then you need to change your code twice if you want to add/remove actions
@kingkero in effects was useless the first control, the switch is enough

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.