开发者

Validate if form data is a present select input option

I have a select input:

<label for="gender">Gender:</label>
<select id="gender" name="gender">
    <option value="Male">Male</option>
    <option value="Female">Female</option>
</select>

How to validate whether submitted data belongs to开发者_开发技巧 select input?

I have tried:

<?php
if ($_POST['gender'] !== 'Male' || $_POST['gender'] !== 'Female') {
      // perform redirect
}


A cleaner way to do it would be

$options = array( 'Male', 'Female' ); 

if( !in_array( $_POST['gender'], $options  ) )  // if Male or Female are not in $_POST 
    // redirect 


if ($_POST['gender'] != 'Male' && $_POST['gender'] != 'Female') {
      // perform redirect
}

The above will redirect if neither option is checked. But personally, I prefer to do a '--Choose--' option, and simply check against it.

<label for="gender">Gender:</label><select id="gender" name="gender">
<option value="0" selected=selected>--Choose--</option>
<option value="Male">Male</option>
<option value="Female">Female</option>
</select>

if ($_POST['gender'] != '0') {
      // perform redirect
}

Also, your original will work with:

if ($_POST['gender'] == 'Male' || $_POST['gender'] == 'Female') {
      // perform redirect
}


You can also use this method.

<?php
if ( isset($_POST['submit']) ) {
    $_POST = array_map( 'stripslashes', $_POST );
    extract( $_POST );

    if ( !isset($Male) && !isset($Female) ) {
    // redirect
    }
}
?>


You should avoid passing literal values altogether when these are in a known range/domain.

The form can be generated using an indexed value, e.g.

<?php
$options = [];
$options['gender'] = [1 => 'Male', 2 => 'Female'];
?>
<label for="gender">Gender:</label>
<select id="gender" name="gender">
    <?php foreach ($options['gender'] as $i => $name):?>
    <option value="<?=$i?>"><?=$name?></option>
    <?php endforeach;?>
</select>

Then your input validation logic would simply check for value presence in the $options array, e.g.

<?php
if (isset($options['gender'][$_POST['gender']])) {
    // 
}

Furthermore, consider using existing form generation tools (e.g. https://github.com/gajus/dora) and input validation libraries (https://github.com/gajus/vlad). I am the author of both libraries, and each library will refer you to the existing alternatives. The purpose of using an existing library for generating form and handling input validation is to avoid re-inventing the wheel and protecting yourself from silly security bugs that are often overlooked when handling forms, e.g. XSS.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜