用PHP设置Cookie;但没被发现?

时间:2012-05-22 18:45:24

标签: php session cookies isset

当用户登录时,这是我的用户功能:

public function login($user) {
    global $database;
    if ($user) {

        $_SESSION['user_id'] = $user->id;
        $this->user_id = $_SESSION['user_id'];

        $_SESSION['username'] = $user->username;
        $this->username = $_SESSION['username'];

        setcookie('user_id', $this->user_id, time() + (60 * 60 * 24 * 14));
        setcookie('username', $this->username, time() + (60 * 60 * 24 * 14));

        $this->logged_in = true;

    }
}

当我查看Chrome中的Cookie时,我发现有两个与此相关的Cookie:
1表示user_id,1表示用户名。

但是当浏览器关闭并且我尝试回来时,它将无法检测到cookiee:这是过程:

class Session {

     // Most of the class has been edited out; the code above is also a method in this clas. Removed so it's not duplicated.


     private $logged_in = false;
     public $user_id; // yes I realize this is insecure
     public $username; // yes I realize this is insecure

     function __construct() {
          session_start();
           $this->check_login();
     }

    public function is_logged_in() {
        return $this->logged_in;
    }

   private function check_login() {

    if (isset($_COOKIE['user_id']) && (isset($_COOKIE['username']))) {
        $_SESSION['user_id']= $_COOKIE['user_id'];
        $_SESSION['username'] = $_COOKIE['username'];

    } else { // When I test, below shows up showing it doesn't think Cookie is set.
        echo "Cookie not set in check_login().<br />";
    }

    if (isset($_SESSION['user_id'])) {
        $this->user_id = $_SESSION['user_id'];
        $this->username = $_SESSION['username'];
        $this->logged_in = true;
    } else {
        unset($this->user_id);
        $this->logged_in = false;

    }
  }

 $session = new Session();

}

1 个答案:

答案 0 :(得分:2)

尝试设置路径和域。

setcookie('user_id', $this->user_id, time() + 3600, '/', '.yourdomain.com');

如果将路径保留为空,则cookie将仅在当前目录中“处于活动状态”。例如,如果您的登录脚本是http://example.com/user/login.php,那么当您打开http://example.com时,浏览器将不会设置Cookie。