2014-11-02 22 views
-3

如何在用戶嘗試訪問index.php時訪問index.php但未登錄get的重定向到login.php?如何鎖定未登錄用戶的頁面

編輯

我還沒有嘗試任何事情,我只有代碼登錄用戶

+0

顯示的代碼來破壞會話(這會破壞所有的會話變量)是什麼你已經嘗試 – SReject 2014-11-02 02:57:56

+0

我還沒有嘗試過任何東西,我只有登錄用戶的代碼 – 2014-11-02 02:59:47

+0

你問過之前試過搜索堆棧溢出或谷歌? – amaster 2014-11-02 03:16:15

回答

1

你需要一個會話varaiable集:

// Required to set and read sessions 
session_start(); 
// Conditional if logged in 
if(isset($_SESSION['username'])) { 
     // do logged in stuff 
    } 
else 
    // Redirect if not logged in 
    header("Location: login.php"); 
+0

感謝兄弟,我會在9分鐘內接受:) – 2014-11-02 03:02:48

+1

您應該退出腳本以防止任何代碼泄露給未登錄的用戶(請參閱我的答案) – Luc 2014-11-02 03:25:17

1

當您啓動用戶會話,設置一個$_SESSION變量:

/* login_submit.php */ 

// Check if username and password are correct 
if ($username == $valid_username && $password == $valid_password) { 
    session_start(); // Start the session 
    $_SESSION["session_secret"] = "a_secret_string"; // Set a secret variable 
    header("Location: index.php"); // Redirect the user to index.php 
} 

然後,檢查該變量,看是否有用戶登錄:

/* index.php */ 

// Resume the session 
session_start(); 

// Check if the user is logged in 
if ($_SESSION["session_secret"] != "a_secret_string") { 
    // Nope! This user is NOT logged in! 
    header("Location: login.php"); // Redirect the user to login.php 
    exit(); // Exit the script so code doesn't get leaked 
} 

// Code for logged in users goes below 

記住,當用戶註銷使用session_destroy();

相關問題