从动作表单脚本检索变量时未定义变量


Undefined variable while retrieving variable from action form scripts

<?php 
    if($_POST) {
         //not empty
         //atleast 6 characters long
         $errors = array();
         //start validation
         if(empty($_POST['email'])) {
             $errors['email1'] = "<p style='color:red;font-family: BCompset, Arial, Helvetica, sans-serif;font-size:30px;'>Please write down your email!</p>";
         }
         //check errors
         if(count($errors) == 0) {
             //redirect to success pages
             header("Location: success.php");
             exit();
          }
    }
    ?>
    <form action="" method="POST" class="searchform" dir="ltr">
      <input type="text" name="email" placeholder="Your email address"/>
      <button name="submit" type="submit" class="btn btn-default"><i class="fa fa-arrow-circle-o-right"></i></button>
      <p><?php if(isset($errors['email1'])) echo $errors['email1']; ?></p>
      <?php if(count($errors) == 0){
         echo "<p id='para' dir='rtl'>
         You can add your email to get the latest updates.</p>";
       } ?>
    </form>

我想显示段落id='para'(第31行),当表单还没有提交,如果用户点击提交按钮没有输入他的电子邮件地址,错误消息将弹出,该段将不再显示。为此,我设置了if(count($errors) == 0),但在第31行上得到了未定义变量错误消息。也许是因为我不能从动作脚本的变量,直到表单没有提交。请问我的问题有什么解决办法吗?

试试这个代码:-

<?php 
 $errors = array();
if($_POST)
    {
        //not empty
        //atleast 6 characters long
        //start validation
        if(empty($_POST['email']))
        {
            $errors['email1'] = "<p style='color:red;font-family: BCompset, Arial, Helvetica, sans-serif;font-size:30px;'>Please write down your email!</p>";
        }
        //check errors
        if(count($errors) == 0)
        {
            //redirect to success pages
            header("Location: success.php");
            exit();
        }
    }
?>
<form action="" method="POST" class="searchform" dir="ltr">
                                <input type="text" name="email" placeholder="Your email address"/>
                                <button name="submit" type="submit" class="btn btn-default"><i class="fa fa-arrow-circle-o-right"></i></button>
                                <p><?php if(isset($errors['email1'])) echo $errors['email1']; ?></p>
                   <?php if(count($errors) == 0){echo "<p id='para' dir='rtl'>You can add your email to get the latest updates.</p>";}?>
</form>

问题是您的<form>if($_POST)之外,因此将显示是否设置了$_POST。但是$errors只在if内部设置。有两种简单的方法可以解决这个问题:

  1. $errors的初始化移到if之前

  2. 使用if(empty($errors)代替if(count($errors) == 0)。如果变量没有设置,empty()不会抱怨