在PHP中实现Sessions和Cookies的正确方法?

时间:2014-01-13 21:10:58

标签: php session cookies

我很简单,无法处理实现Cookie和会话的正确方法。当我认为我正确地实现了代码时,我每次都有另一个错误。

当用户注册或登录时,我运行此代码:

session_start();
$_SESSION['SESS_USER_ID'] = $user_id;
$_SESSION['SESS_USER_NAME'] = $user_username;
$_SESSION['SESS_USER_EMAIL'] = $user_email;
$_SESSION['SESS_LOGGED'] = TRUE;
session_write_close();

setcookie("COOK_USER_ID",$user_id,time()+(3600*24*365));
setcookie("COOK_USER_NAME",$user_username,time()+(3600*24*365));
setcookie("COOK_USER_EMAIL",$user_email,time()+(3600*24*365));
setcookie("COOK_LOGGED",TRUE,time()+(3600*24*365));

在我要保护的每个页面上,我运行以下代码:

session_start();

if(isset($_SESSION['SESS_LOGGED']) && isset($_COOKIE['COOK_LOGGED']))
{ 
} 
elseif (isset($_COOKIE['COOK_LOGGED'])) {
    $_SESSION['SESS_USER_ID'] = $_COOKIE['COOK_USER_ID'];
    $_SESSION['SESS_USER_NAME'] = $_COOKIE['COOK_USER_NAME'];
    $_SESSION['SESS_USER_EMAIL'] = $_COOKIE['COOK_USER_EMAIL'];
    $_SESSION['SESS_LOGGED'] = TRUE;
    session_write_close();
}
else { 
     include_once("register.php");
     exit();
}

当用户注销时,我运行以下代码:

if (isset($_GET['logout'])) {
    //Destroy Session
    session_start();
    $_SESSION = array(); 
    session_unset();
    session_destroy();
    header("Location: index.php");

    //Unset the Cookies
    if (isset($_SERVER['HTTP_COOKIE'])) {
        $cookies = explode(';', $_SERVER['HTTP_COOKIE']);
        foreach($cookies as $cookie) {
            $parts = explode('=', $cookie);
            $name = trim($parts[0]);
            setcookie($name, '', time()-1000);
            setcookie($name, '', time()-1000, '/');
        }
    }
    exit();
}

但是当我关闭浏览器并再次启动它时,总会有一种奇怪的行为,其中没有正确设置cookie等。

我不知道我做错了什么。在我首先运行的所有页面ob_start();上,因此问题不能与标题相关。

0 个答案:

没有答案