PHP防止HTML列表的错误数据收集(选择,复选框,广播)

In order to prevent bad data collection, I was thinking about a way to prevent unwanted values from being accepted by my PHP code.

I'm using the same list to populate the values that I validate against. This would apply to drop downs, radios, and checkboxes.

Granted, this is a very simplified example, but I just wanted to run this idea past some other programmers to see if I'm way off base here.

// get form value
$name = $_POST['color'];

// form list values
$arr =  array("blue", "red", "green");

// build options
for($i = 0, $size = sizeof($arr); $i < $size; ++$i)
{
echo '<option value="' . $arr[$i] . '">' . $arr[$i] . '</option>';
}

// verify value is valid
if (in_array($name, $arr)) {
    // valid value
}

I believe this is a good way to do it, though I'd probably do all the logic of checking right at the top of the script, ie:

// set the error flag
$error_flag = false;

// form list values
$arr =  array("blue", "red", "green");

if(isset($_POST)){
    // get form value
    $name = $_POST['color'];

    // verify value is valid
    if (in_array($name, $arr)) {
        // valid value
    } else {
        // error - you selected an invalid value!
        $error_flag = true;
    }

    if($error_flag == false){
        // process data and save to database, etc etc
    }
}

if($error_flag == true){
    // display the error
}

// build options
for($i = 0, $size = sizeof($arr); $i < $size; ++$i){
    echo '<option value="' . $arr[$i] . '">' . $arr[$i] . '</option>';
}

I've added in an error flag so you can also notify end users of what they've done wrong and allow them to complete the form again. Of course you can expand it so the correct fields 'remember' the data that was already sent before hand, whilst indicating which fields were bad.

Seems like the way to go!

Not sure if this was just a quick sketch, but rather use foreach

for($i = 0, $size = sizeof($arr); $i < $size; ++$i){
    echo '<option value="' . $arr[$i] . '">' . $arr[$i] . '</option>';
}

becomes

foreach($arr AS $v){
    echo '<option value="' . $v . '">' . ucfirst($v) . '</option>';
}