0

ユーザーがログインすると、次のユーザー関数が表示されます。

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を見ると、これに関連する2つのCookieが見つかります。1つ
はuser_id用、もう1つはusername用です。

しかし、ブラウザを閉じて戻ってきようとすると、Cookieが検出されません。プロセスは次のとおりです。

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();

}
4

1 に答える 1

2

パスとドメインを設定してみてください。

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

パスを空のままにしておくと、Cookie は現在のディレクトリ内でのみ「アクティブ」になります。たとえば、ログイン スクリプトがhttp://example.com/user/login.phpの場合、 を開いたときhttp://example.comに、ブラウザは Cookie を設定しません。

于 2012-05-22T18:52:13.527 に答える