如何检查下拉框是否与if语句匹配[PHP]

时间:2014-04-28 04:04:10

标签: php html

我一直在编写一个脚本,而我只是陷入了一个小部分。我正在检查以确保用户提交的表单是安全的。但是我不知道如何接近下拉框,这是我到目前为止的代码:

if ($_POST['type'] != '1' || $_POST['type'] != '2' || $_POST['type'] != '3') // Checks to see if the submitted type matches, prevents exploiting.
{
    $supportErrors[] = "Support type you've chosen was not found, possibly trying to exploit this script?";
}

我不确定这是否是检查其价值的正确方法。对于脚本的这一部分,这是我的HTML方面:

<select name="type" id="type" size="1" style="border: 1px solid #000000; background-color: #FFFFFF;">
      <option value="1" selected>Support</option>
      <option value="2">Question</option>
      <option value="3">Complaint</option>
</select>

现在,根据我的理解,值是发布的数据VIA'type' - 所以,在我看来,它不应该发布该值(1或2或3),然后在PHP方面,它检查如果不是1,2或3?

4 个答案:

答案 0 :(得分:2)

in_array()是一个很好的解决方案,检查1件事是否匹配多个选项之一

if (!in_array($_POST['type'],array(1,2,3))){..}

你应该在开启时出错:

error_reporting(E_ALL);
ini_set('display_errors', 1);

答案 1 :(得分:1)

您需要将条件逻辑从OR更改为AND:

if($_POST['type'] != '1' && $_POST['type'] != '2' && $_POST['type'] != '3')...

答案 2 :(得分:0)

确保使用ISSET检查表单是否已发布

<?php
if ( isset( $_POST['type'] ) and $_POST['type'] != '1' || $_POST['type'] != '2' || $_POST['type'] != '3') // Checks to see if the submitted type matches, prevents exploiting.
{
    $supportErrors[] = ("Support type you've chosen was not found, possibly trying to exploit this script?");
}
?>

答案 3 :(得分:0)

//  Assumimg type as a numeric value , I might achieve it like this

    $type = 0;

    if( isset( $_POST['type'] ) ) $type = trim( $_POST['type'] ) * 1;

    if( $type < 1 )
    {
        $supportErrors[] = "Please specify type";
    }
    elseif( $type > 3 )
    {
        $supportErrors[] = "Invalid type";
    }