简体   繁体   中英

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);
    }
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM