如何锁定未登录用户的页面

时间:2014-11-02 02:56:39

标签: javascript php mysql

如果用户在没有登录时尝试访问index.php,我怎么能这样做?重定向到login.php?

修改

我没有尝试任何东西,我只有登录用户的代码

2 个答案:

答案 0 :(得分:1)

您需要一个会话变量集:

// 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");

答案 1 :(得分: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();

注销时,请记住销毁会话(会破坏所有会话变量)