Search code examples
phpsessioncookiesremember-mestay-logged-in

PHP: Remember Me, Stay logged in doesn't work


In my PHP project, I want to add a user remember me checkbox so that everybody can choose to stay logged in:

Until now I do my normal log in like:

public function loginUser($psMail, $psPwd, $pnRememberMe = 0) {
   // Check credentials and so on
   // If mail and password matches
   if(CREDENTIALS OKAY) {
      $_SESSION["username"] = "foo";
      $lnExpire = time() + 3600 * 24 * 60;
      setcookie("remember", base64_encode(USERID), $lnExpire);
      setcookie("rememberToken", md5(SOMESTUFF), $lnExpire);
   }
}

When I log in, I can see the created cookie variables with:

print_r($_COOKIE);

Now I try to leave the site with my logout function:

// Unset the session variables
$_SESSION = array();
// Destroy the session.
session_destroy();

But now, when I am at the landing page, there are also my cookies gone? Could this be because of my session site settings?

ini_set("session.use_only_cookies", "1");
ini_set("session.use_trans_sid", "0");

Solution

  • php function setcookie has fourth argument path, from documentation "The path on the server in which the cookie will be available on". By default it set path to actual your directory. Try set "/" Then it will be available for all domain. http://php.net/manual/en/function.setcookie.php