ipel
ipel

Reputation: 1348

php check that the $_POST sent are allowed fields

I'm working on code to validate that all the $_POST variables are within an 'allowed' list to prevent hacking.

The idea is that if I have 4 fields in a form and someone send an additional post variable an error is shown.

My first question is: is that useful?

This is my PHP code to check the post sent, but I don't know why it doesn't work:

$allowed = array(
    'field1',
    'field2',
    'select1',
    'textarea1',
    'submit_button'
);

foreach($_POST as $k => $v) { 
    if(!array_key_exists($k, $allowed)) {
        die('error with field: '.$k);
    }
}

Upvotes: 0

Views: 70

Answers (1)

mleko
mleko

Reputation: 12243

Use in_array instead of array_key_exists

$allowed = array(
    'field1',
    'field2',
    'select1',
    'textarea1',
    'submit_button'
); 
foreach($_POST as $k => $v) { 
    if(!in_array($k, $allowed)) {
        die('error with field: '.$k);
    }
}

This can be useful, but you should perform real validation of received form anyway.

Upvotes: 1

Related Questions