PHP会话问题

时间:2011-07-14 13:23:26

标签: php mysql session login

我有一个登录页面和一个“会员区域”页面,登录代码在这里:

的login.php

if ($account->is_logged_in())
{
    $route->to(ACCOUNT_URL);
}

elseif (isset($_POST['username']))
{
    if ($account->authenticates())
    {
        if ($account->log_in()) $route->to(ACCOUNT_URL);
    }
    else
    {
        $flash->set('error', 'The credentials you provided are incorrect.');
    }
}

功能(在不同的文件中)

public function log_in ()
{
    session_unset();
    session_destroy();

    if(session_start())
    {
        $_SESSION['logged_in'] = true;
        $_SESSION['username'] = $_POST['username'];
    }
}

public function authenticates ()
{
    $username = $_POST['username'];
    $password = $_POST['password'];
    if (ctype_alnum($username) && ctype_alnum($password))
    {
        $username = mysql_real_escape_string(filter_var($username, FILTER_SANITIZE_STRING));
        $password = $this->encrypt(mysql_real_escape_string(filter_var($password, FILTER_SANITIZE_STRING)));

        $sql = "SELECT * FROM users WHERE username = '$username' AND password = '$password'";

        $result = mysql_query($sql);

        if (mysql_num_rows($result) == 1)
        {
            return true;
        }
        else 
        {
            return false;
        }
    }
    else
    {
        return false;
    }
}

然后是我的会员区域页面:

if ($account->is_logged_in())
{
    echo 'logged in';
}
elseif (!$account->is_logged_in())
{
    echo 'not logged in';
    echo session_id();
    print_r($_SESSION['logged_in']);
}

login.php重定向我(意味着它验证了我的帐户),但当我到达members.php时,它会回复“未登录”,这就是全部。

2 个答案:

答案 0 :(得分:4)

您需要在session_start()的顶部(以及需要访问members.php的任何网页)致电$_SESSION

// Must initiate the session to test if logged in.
session_start();
if ($account->is_logged_in())
{
    echo 'logged in';
}
elseif (!$account->is_logged_in())
{
    echo 'not logged in';
    echo session_id();
    print_r($_SESSION['logged_in']);
}

答案 1 :(得分:1)

您是否在所有使用会话的脚本的开头都有session_start()