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

Php 从操作表单脚本检索变量时未定义变量,php,forms,Php,Forms,尝试以下代码:- <?php if($_POST) { //not empty //atleast 6 characters long $errors = array(); //start validation if(empty($_POST['email'])) { $errors['email1'] = "<p style='color:red;font

尝试以下代码:-

<?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>

问题是您的
if($\u POST)
之外,因此将显示是否设置了
$\u POST
。但是
$errors
仅在
if
中设置。有两种简单的方法可以解决此问题:

  • $errors
    的初始化移动到
    if
    之前

  • 使用
    if(empty($errors)
    代替
    if(count($errors)==0)
    empty()
    如果变量未设置,则不会抱怨


  • if(empty($errors))
    在这种情况下可能会有所帮助。这样,错误消息将消失,但段落仍然无法显示!
    <?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>