2016-11-05 61 views
0

我想過使用php頭重定向驗證成功。但是,這似乎打破了我。那麼我如何實現一個。條件是所有的驗證都經過驗證,那麼它只會重定向。驗證後重定向到成功頁面

<?php 
     // define variables and set to empty values 
     $nameErr = $lastnameErr = $emailErr = $passwordErr = $confirmpasswordErr = $checkboxErr= ""; 
     $name = $lastname = $email = $password = $confirmpassword = $checkbox = ""; 

     if ($_SERVER["REQUEST_METHOD"] == "POST") { 

      if (empty($_POST["firstname"])) { 
       $nameErr = "First Name is required"; 
      }else { 
       $name = test_input($_POST["firstname"]); 
      } 

       if (empty($_POST["lastname"])) { 
       $lastnameErr = "Last Name is required"; 
      }else { 
       $name = test_input($_POST["lastname"]); 
      } 

      if (empty($_POST["email"])) { 
       $emailErr = "Email is required"; 
      }else { 
       $email = test_input($_POST["email"]); 

       // check if e-mail address is well-formed 
       if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { 
        $emailErr = "Invalid email format"; 
       } 
      } 


      if(!empty($_POST["password"]) && ($_POST["password"] == $_POST["confirmpassword"])) { 
       $password = test_input($_POST["password"]); 
       $confirmpassword = test_input($_POST["confirmpassword"]); 
       if (strlen($_POST["password"]) <= '8') { 
        $passwordErr = "Your Password Must Contain At Least 8 Characters!"; 
       } 
       elseif(!preg_match("#[0-9]+#",$password)) { 
        $passwordErr = "Your Password Must Contain At Least 1 Number!"; 
       } 
       elseif(!preg_match("#[A-Z]+#",$password)) { 
        $passwordErr = "Your Password Must Contain At Least 1 Capital Letter!"; 
       } 
       elseif(!preg_match("#[a-z]+#",$password)) { 
        $passwordErr = "Your Password Must Contain At Least 1 Lowercase Letter!"; 
       } 
      } 
      elseif(empty($_POST["password"])) { 
       $passwordErr = "Password not filled at all"; 
      } 

      elseif(!empty($_POST["password"])) { 
       $confirmpasswordErr = "Password do not match"; 
      } 

     if(!isset($_POST['checkbox'])){ 
     $checkboxErr = "Please check the checkbox"; 
     } 
     else { 
       $checkbox = test_input($_POST["checkbox"]); 

      } 









     } 



     function test_input($data) { 
      $data = trim($data); 
      $data = stripslashes($data); 
      $data = htmlspecialchars($data); 
      return $data; 
     } 
     ?> 

    header('Location: http://www.example.com/'); 
+1

爲什麼PHP在header之前關閉。 – shubham715

+0

這只是一個例子。我知道你必須在php標籤之前 – Joal

回答

0

設置$錯誤= 1,如果任何條件得到失敗,並在底部檢查,如果($錯誤!= 1),然後重定向 ,你也可以使用JavaScript重定向如果頭部不工作

-1
  1. 看看結束「?>」 - Tab。頭文件會生成一個html頭文件,但它是一個php函數,應該放在?php?>括號中。

  2. 考慮使用HTML5輸入驗證 - 節省一些代碼和服務器往返讓瀏覽器做驗證

  3. 省略結束?「>」乾脆。它沒有必要,並且可能導致很難看到錯誤,當有內容時 - 甚至空白 - 在「?>」之後 - >「

  4. 考慮使用帶有適當參數的filter_input函數來訪問$ _POST並設置變量。

相關問題