PHP仅在提交表单之前注意到未定义的索引

时间:2016-10-19 10:07:24

标签: php html forms

我正在尝试从表单进行简单的值检查,并且我想为用户输入的值分配一些变量。 我做了这样的表格:

<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="POST">
                <label for="raspuns1"><span class="glyphicon glyphicon-pencil"></span> Raspuns subpunct a</label>
                <input type="text" class="form-control" name="raspuns1" placeholder="Raspuns a"><br>
                <label for="raspuns2"><span class="glyphicon glyphicon-pencil"></span> Raspuns subpunct b</label>
                <input type="text" class="form-control" name="raspuns2" placeholder="Raspuns b"><br>
                <label for="raspuns3"><span class="glyphicon glyphicon-pencil"></span> Raspuns subpunct c</label>
                <input type="text" class="form-control" name="raspuns3" placeholder="Raspuns c"><br>
                <label for="raspuns4"><span class="glyphicon glyphicon-pencil"></span> Raspuns subpunct d</label>
                <input type="text" class="form-control" name="raspuns4" placeholder="Raspuns d"><br>
                <button type="submit" class="btn btn-success glyphicon glyphicon-check"> Verifica răspunsurile</button>
    </form>

这是php代码

<?php 
$corect1="raspunsulcorect";
$corect2="raspunsulcorect";
$corect3="raspunsulcorect";
$corect4="raspunsulcorect";

if(isset($_POST['submit']))
{
$raspuns1=$_POST['raspuns1'];
$raspuns2=$_POST['raspuns2'];
$raspuns3=$_POST['raspuns3'];
$raspuns4=$_POST['raspuns4'];
}

?>

问题在于,当我打开页面时,它会显示我

Notice: Undefined index: raspuns1 in A:\XAMPP\htdocs\Copie\Teste\test1-geometrie.php on line 5

Notice: Undefined index: raspuns2 in A:\XAMPP\htdocs\Copie\Teste\test1-geometrie.php on line 6

Notice: Undefined index: raspuns3 in A:\XAMPP\htdocs\Copie\Teste\test1-geometrie.php on line 7

Notice: Undefined index: raspuns4 in A:\XAMPP\htdocs\Copie\Teste\test1-geometrie.php on line 8

按下提交按钮后,一切正常,但如果第一次打开页面,则会显示。我究竟做错了什么? 首先如果不应该让程序检查变量

1 个答案:

答案 0 :(得分:0)

继续添加一个方法,在访问$ _POST超全局之前检查这是否是POST请求。

示例:

function isPost() {
  return strtolower($_SERVER['REQUEST_METHOD']) == 'post';
}

在您的代码中(假设您已定义上述功能):

if(isPost() && isset($_POST['submit']))
{
$raspuns1=$_POST['raspuns1'];
$raspuns2=$_POST['raspuns2'];
$raspuns3=$_POST['raspuns3'];
$raspuns4=$_POST['raspuns4'];
}

从$ _GET和$ _POST超全局变量中获取值时,还要检查filter_input和filter_var函数。