0

I'm setting a Cookie with the following code:(admin.php)

  if ($_POST['stayLoggedIn'] == '1') {
    setcookie("id", $row['id'], time() + 60*60*24*365);
  }
  header("Location: addtip.php");

I can't get the cookie to unset, I've searched the site and the following code should be correct but it's not working;(admin.php)

  if (array_key_exists("logout", $_GET)) {
    unset($_SESSION);
    setcookie("id", "", time()-60*60);
    $_COOKIE["id"] = "";
  }

Testing the cookie has been unset using the following code on the "loggedinpage" which would return to the admin login page if cookie was unset (addtip.php)

session_start();
if (array_key_exists("id", $_COOKIE)) {
    $_SESSION['id'] = $_COOKIE['id'];
}
if (array_key_exists("id", $_SESSION)) {
    echo "<a href='admin.php?logout' class='btn btn-danger btn-logout'>Log Out</a>";
} else {
    header("Location: admin.php");
}
oversoon
  • 350
  • 2
  • 7
  • 21
  • How do you check if the cookie was unset? – John Conde Sep 09 '18 at 18:05
  • @JohnConde Updated my question – oversoon Sep 09 '18 at 18:09
  • Is the code you just added on a separate page that requires a redirect to get to? The cookie won't be actually unset until the next page load. At that point it will no longer exist and not be sent to the server. – John Conde Sep 09 '18 at 18:10
  • 1
    On a side note, if you want to make a cookie expire, make the date really far in the past. It works around timing issues between the server and browser. And use `strtotime()` to do it as it is much clearer than `time()-60*60`. `setcookie("id", "", strtotime('-1 year'));` – John Conde Sep 09 '18 at 18:12
  • @JohnConde I added the filenames i'm using in brackets in the question – oversoon Sep 09 '18 at 18:16

1 Answers1

1

The problem is that you aren't clearing the $_COOKIE['id'] value correctly. You are setting it to an empty string. The idea is correct, but you have to use unset() to remove the entry from the $_COOKIE array. If you don't do that, the if() condition array_key_exists("id", $_COOKIE) will result in true even though there is no any usable value in it. And setting the $_SESSION['id'] with an empty string as well would make the following if() condition array_key_exists("id", $_SESSION) result in true as well. Therefore you get the logout link.

if (array_key_exists("logout", $_GET)) {
    unset($_SESSION);
    setcookie("id", "", strtotime('-1 year')); // send a header to remove the cookie
    unset($_COOKIE["id"]); // remove the cookie for the remaining CURRENT http request
}

Not sure if unset($_SESSION); is the right thing to do, you might want to use session_destroy(); instead/additionally.

Progman
  • 16,827
  • 6
  • 33
  • 48