Merbin Joe
Merbin Joe

Reputation: 688

The cookie value not removed in php

I am new to php, but I have 2 years experience in asp.net. When I am calling logout.php It doesn't doesn't removed the cookie values.

<?php

if (isset($_COOKIE['C_username'])) {

  unset($_COOKIE["C_username"]);
  unset($_COOKIE["C_password"]);


  setcookie("C_username", '', time() - 3600);
  setcookie("C_password", '', time() - 3600);

}

echo "<script>alert('".$_COOKIE["C_username"]."');</script>" ; //Here the cookie value is found.

header( 'Location: ../index.php');
?>

After redirecting to another index.php, there also the cookie found.

Upvotes: 1

Views: 43

Answers (1)

RiggsFolly
RiggsFolly

Reputation: 94672

The cookie is not cleared until the page is reloaded by the browser so if you change your javascript to actually look for the cookie on the browser rather than use the PHP (on server) version of it you may get more predictable results.

Also remember that cookies and header() statements must be run before any other data is sent to the browser so your code should be generating an error anyway as your header() statement is after an echo statement.

So try

<?php

if (isset($_COOKIE['C_username'])) {
  setcookie("C_username", '', time() - 3600);
  setcookie("C_password", '', time() - 3600);
  header( 'Location: ../index.php');
  exit;
}

echo '<script>alert(document.cookie);</script>";    

?>

Additional Point:

Dont put passwords in cookies There is no need to do this anyway as if you are using it to log the user on when they re-visit, you dont need the password you just set the fact that thay are logged in because you see a cookie, it does not need to have a valid userid/password in that/those cookies.

Also remember that cookies can be turned off by the browser!

Upvotes: 3

Related Questions