2015-05-15 156 views
1

我創建了一個網頁(讓我們稱之爲main.php),並決定在它上面放置一個登錄(文件index.php)。登錄工作正常,但問題是這樣的。如果我直接在瀏覽器中輸入頁面的地址(main.php),它將被打開。 有沒有辦法阻止打開頁面,除非我通過登錄?防止在沒有登錄的情況下打開頁面

如果它是相關的,這是登錄代碼:

<!DOCTYPE html> 
<html > 
    <head> 
     <meta charset="UTF-8"> 
     <title>Login</title> 
    <link rel="stylesheet" href="/css/style.css"> 
    </head> 

    <body> 
     <div class="login_container"> 
      <div id="login-form"> 
       <h3>Login</h3> 
       <fieldset> 
        <form action="checklogin.php" method="post"> 
          <input name="username" type="text" required placeholder="Username"> 
           <input name="password" type="password" required placeholder="*******"> 
           <input type="submit" value="Login"> 
        </form> 
       </fieldset> 
      </div> 
    </div> 
</body> 
</html> 

,並將其引導到:

<?php 

ob_start(); 

    // Define $username and $password 
    $username=$_POST['username']; 
    $password=$_POST['password']; 

    $username = stripslashes($username); 
    $password = stripslashes($password); 
    $username = pg_escape_string($username); 
    $password = pg_escape_string($password); 

if($username == "username" && $password == "password"){ 
     $_SESSION['username']="username"; 
     $_SESSION['password']="password"; 
     header("location:main.php"); 
} 
else header("location:index.php"); 
ob_end_flush(); 
?> 
+0

我不知道是否有任何方法可以防止打開頁面,除非您經過登錄,但如果用戶嘗試在未登錄的情況下訪問main.php,仍然可以將用戶重定向到登錄頁面 – Cr3aHal0

+2

非常基本:'if (!isset($ _ SESSION ['username'])){...沒有登錄...}'在你想保護的每一頁上。 –

回答

1

你需要檢查,對每個需要的登錄請求,該用戶已登錄並獲得授權。

查看此問題的好方法是將請求URL看作是程序輸入的一部分。就像輸入cookies和GET/POST參數一樣。

main.php將返回包含數據的頁面或登錄請求。

+0

但是,如果我有很多頁面(main.php和其他頁面,我從中導航),並且我不希望它們中的任何一個在沒有登錄的情況下打開,那麼如果有一個頁面,我是否檢查其中的每一個登錄完成? –

0

當然。 檢查用戶當前是否在登錄頁面時使用php sessions如果他們沒有登錄發送錯誤或將他們重定向到其他地方。

相關問題