1

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.

RiggsFolly
  • 93,638
  • 21
  • 103
  • 149
Merbin Joe
  • 611
  • 6
  • 27
  • I tried without using the setcookie line. But no use – Merbin Joe Jul 19 '15 at 13:33
  • 4
    As I see you are using cookies for a login system, Cookies have a way of lingering. I recommend not doing so at all, due to the security problems (VERY easy to hack). Sessions are quite a bit safer and easier to manage (e,g, `session_destroy()` ) – nomistic Jul 19 '15 at 13:40
  • Some reading material about the [remember me](http://stackoverflow.com/questions/1354999/keep-me-logged-in-the-best-approach)-functionality – DarkBee Jul 19 '15 at 13:55
  • I strongly suggest reading a bit about cookies and sessions and perhaps make sure you really want/need to be using cookies. Some reading: http://stackoverflow.com/a/3150957/2632129 - http://stackoverflow.com/a/5232967/2632129 - http://stackoverflow.com/a/1563507/2632129 – James Jul 19 '15 at 13:58

1 Answers1

3

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!

RiggsFolly
  • 93,638
  • 21
  • 103
  • 149