2016-03-31 25 views
1

我很難將頁眉重定向到index.html從我的登錄頁面。我不確定標題甚至是要走的路,但這是我能夠在頁面重定向中找到的所有東西。php重定向到不同的頁面trouble

這段代碼只是一個簡單的登錄頁面,用於檢查MySQL數據庫的用戶名和密碼。

我遇到的問題是,如果語句中:

if(mysqli_num_rows($res) == 1){ 
     header("Location: index.php"); 
     exit(); 
} 

爲login.php中全碼:

<?php 
     //Connects to MySQL database using sql_connect.php 
     require "sql_connect.php"; 
    ?> 

    <?php 
     if(isset($_POST['username'])) { 
      $username = $_POST['username']; 
      $password = $_POST['password']; 
      $sql = "SELECT * FROM login_test WHERE username='".$username."' AND password='".$password."' LIMIT 1"; 
      $res = mysqli_query($connection, $sql); 
      if(mysqli_num_rows($res) == 1){ 
       header("Location: index.php"); 
       exit(); 
      } else { 
       echo "Invalid login information!"; 
       exit(); 
      } 
     } 
    ?> 

    <!DOCTYPE html> 
     <html lang="en"> 
     <head> 
      <meta charset="UTF-8"> 
      <title>login</title> 
      <link rel="stylesheet" href="../style.css"> 
     </head> 
     <body> 
      <form name="login" method="post" action="login.php"> 
       <h3>Login</h3> 
       <p>Username: </p><input type="text"name="username"> 
       <p>Password: </p><input type="password" name="password"> 
       <br/> 
       <input type="submit"name="submit"value="log in"> 
      </form> 
      <script src="../script.js" type="text/javascript"></script> 
     </body> 
    </html> 

雖然我敢肯定,我的代碼的其餘部分是遠遠不夠完善我真的在看如何重定向到一個新的頁面,如果用戶在數據庫中進行身份驗證?在我的情況下,是否有比標題更好的選擇,還是我只是實現它錯了?

+0

阻止未經過身份驗證的用戶直接訪問該頁面的原因是什麼? – Tim

+0

檢查你的服務器日誌,看看你是否得到'Headers already sent'警告。 – Barmar

+0

目前沒有。我自學一步 – Hunter

回答

1

我以前用過php頭,但是經驗不好。
通常我使用JavaScript

echo '<script type="text/javascript">' . "\n"; 
if(isset($from)) 
{ 
    echo 'window.location="..";'; 
} 
else 
{ 
    echo 'window.location="..";'; 
} 
echo '</script>'; 
0

header()函數沒有工作可以用你的 「mysqli_num_rows($水庫)== 1」 的結果是假的原因。

「位置」和「index.php」之間沒有空格,如: header(「Location:index.php」);

或者您可以創建一個php函數並使用JavaScript,它是一種避免這種情況的好方法。

function redirect($url, $prompt) { 
    $js_string = "<script>"; 
    $js_string .= $prompt ? "alert('". $prompt ."');" : ""; 
    $js_string .= "window.location = '{$url}';"; 
    $js_string .= "</script>"; 
    exit($js_string); 
}