Conjunto de cookies en PHP; pero no ser encontrado?

When a user logs in, here is my user function:

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;


When I look at the Cookiees in Chrome, I find two cookies relating to this:
1 for user_id, 1 for username.

But when the browser is closed and I try to come back, it will not detect the cookiee: Here is the process:

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

    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 {
        $this->logged_in = false;


 $session = new Session();


preguntado el 22 de mayo de 12 a las 19:05

¿Qué print_r($_COOKIE); print on the 1) next load after setting the cookie and 2) after closing and reopening the browser? -

After I log in, it shows the correct cookie name and value. This: [user_id] => 1 [username] => Joe User. It also shows the PHPSESSID and a couple of Google Analytic cookies. When I reopen the browser. It only shows the Google cookies. -

1 Respuestas

Try to set the path and domain.

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

If you leave the path to empty, the cookie will only "active" within the current directory. For example, if your login script is, then when you open, the browser won't set the cookies.

contestado el 22 de mayo de 12 a las 19:05

Question: My login set the cookie in .domain/folder/HERE. The page that the browser opens up to is one directory back: .domain/HERE -- so which path do I use? - elmaestrodelaslechugas

I just figured it out. '/' makes it available for the whole domain. I then had to update my log out script to make it match and it all works perfectly! - elmaestrodelaslechugas

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.