2017-08-03 39 views
1

我對如何在PHP中實現Post/Redirect/Get模式有點困惑。我見過幾個答案,只是在提交表單後添加標題函數;我已經這樣做了,但在驗證輸入字段是否爲空時,它不會打印任何內容,儘管我在運行代碼後添加了頭部函數。我根本找不到如何整合這個,所以我反正問。如果輸入字段爲空,PHP將不會回顯;與PRG模式

<?php 

require '../BACKEND/DB/DB_CONN.php'; 

if(isset($_POST['submit-register'])) { 

    if(empty($_POST['email'])) { 
     echo 'Email cannot be nothing.'; 
    } 

    header("Location: index.php"); 
    die(); 
} 

if(isset($_POST['submit-login'])) { 

    if(empty($_POST['loginUser'])) { 
     echo 'Field Empty.'; 
    } 

    header("Location: index.php"); 
    die(); 

} 

?> 

<div class="forms"> 
     <form method="post" action="index.php" role="form" class="forms-inline register "> 
     <h4>Register</h4> 
      <input type="text" name="email" placeholder="Email Address" autocomplete="off" /> 
      <input type="text" name="username" placeholder="Username" autocomplete="off" /> 
      <input type="password" name="password" placeholder="Password" autocomplete="off" /> 
      <input type="submit" name="submit-register" value="Register" role="button" name="login-btn" /> 
     </form> 
     <form method="post" action="index.php" role="form" class="forms-inline login "> 
     <h4>Login</h4> 
      <input type="text" name="loginUser" placeholder="Username" /> 
      <input type="password" name="loginPass" placeholder="Password" /> 
      <input type="submit" name="submit-login" value="Register" role="button" /> 
     </form> 
    </div> 

我在寫代碼,但是我發現它不工作,我問如何解決這一問題,以及如何實現郵政/重定向/模式安全,我知道有用。

+0

如果有任何信息打印到頁面,則標題無法正常工作。另外,如果頭文件正在工作,您將永遠不會看到該輸出,因爲它會在實際加載頁面之前重定向。 – GrumpyCrouton

+0

@GrumpyCrouton我甚至在打印之前放置了標題,沒有打印任何東西。 – Adam

回答

0

使用標題(路徑)重置頁面。因此,之前打印的任何回聲都將被丟棄。

2

查看submit-register POST操作通過傳遞驗證消息來驗證並重定向到index.php。你需要從頭方法傳遞消息。

在PRG模式中,當您執行包含數據的POST操作但重定向並在發佈後執行GET以維護PRG時,必須將數據傳遞到最後一個目標GET URL。

在您的代碼中,請參閱我已完成的兩種方式,第一個將消息傳遞給索引,但第二個在驗證中發生錯誤時不是PRG。

//PRG.......................................... 
if(isset($_POST['submit-register'])) { 

    if(empty($_POST['email'])) { 
     echo 'Email cannot be nothing.'; 
     $msg = "Email cannot be nothing"; 
    } 

    header("Location: index.php?msg=$msg"); 
    //Get your this message on index by $_GET //PRG 

} 
//Not full PRG with no passing data to destination......................... 
if(isset($_POST['submit-login'])) { 

    if(empty($_POST['loginUser'])) { 
     echo 'Field Empty.'; 
    } 
    else{ 
     header("Location: index.php"); 
    } 

} 

注意在頁眉方法之前不應該在頁面上打印任何東西。這意味着在標題方法之前沒有回聲。

查看第一個是PRG,第二個也是PRG,但不會將您的數據傳遞到目標。

header("Location: index.php?msg=$msg"); 
+0

我在打印任何東西之前放置了標題,但沒有打印任何東西。 – Adam

+0

看到更新後的代碼......和代碼註釋,要打印你必須將你的味精傳遞給index.php,在發佈和重定向之後,通過頭髮起新的獲取請求不會傳遞你的消息,你必須通過你的數據到你PRG模式中的最後一個GET(header method url)操作。 – webDev

+0

好吧,現在我知道它在URL欄中有效,但是如何在不同的地方打印郵件 - 頁面上? – Adam