Search code examples
phpvalidationpostwhitelist

How does this whitelist array affect $_POST data inside the foreach()?


I'm confused as to exactly what this does and how do you use it in your form processing. Does it only remove unwanted $_POST entries that are not in $expected[]? Should I still use $_POST[ 'carModel'] to get the value? Or might there be a better way?

<?php
$expected = array( 'carModel', 'year', 'bodyStyle' );
foreach( $expected AS $key ) {
    if ( !empty( $_POST[ $key ] ) ) {
        ${$key} = $_POST[ $key ];
    }
    else 
    {
        ${$key} = NULL;
    }
}
?>

Solution

  • Right, the pseudo-code ${$variable} is the creation of a new variable, aka:

    $variable = 'carModel';
    $value = 'VW'    
    ${$variable} = $value;
    

    you assign $_POST[$key] to $test, like $test = $_POST[$key]; echo $future; //have the same value of $_POST['future']

    Now you can skip using $_POST['test'] to use $test, all array keys from the white list should be assigned to variables called by the name of the key;

    On your example, the $excepted work like a filter to only assign the variables that's in this array