session_destroy() doesn't log the user out

I am working on a PHP script where a user can log in and log out but the logging out feature does not work. Here is what I have in my logout.php file:

<?php
 include_once("header.php");
 echo session_id()." | ";
 $_SESSION = array();
 // http://us2.php.net/session_destroy
 if (ini_get("session.use_cookies")) {
     $params = session_get_cookie_params();
     setcookie(session_name(), '', time() - 42000,
         $params["path"], $params["domain"],
         $params["secure"], $params["httponly"]
     );
 }
 session_destroy();
 echo session_id();
 include_once("db.php");
 include_once("top-user.php");
 echo "<p>You have successfully logged out.</p>";
 include_once("footer.php");
?>

The first line of header.php is “<?php session_start(); ?>”. I added the if-statement about cookies based on what I found on another website, but it still does not work. I am not manually using cookies, however, but I was not sure if sessions use cookies to store data so I tried that method. The logout.php page displays a sequence of numbers and letters before the vertical bar but nothing after it. However, when I click on a link to another page it says that I am logged in.

I found threads on other message boards when I did a websearch about this problem but nothing helped me. Some of them suggested unsetting the $_SESSION variable, but I am doing that with “$_SESSION = array();”. Some of the threads suggested deleting cookies but I did that with my if-statement.

I just realized that this could be that I am calling “session_start()” at the top of each page. So even after a user logs out, it starts a new session when the user visits a different page. However, it is necessary to start each page with “session_start()” so that when a user is logged in, session data will appear. Instead of testing if a user is logged in with “if(!session_id() == “”)” I could use “if(isset($_SESSION[‘userid’]))”. Is this good practice or the best way to do it? It doesn’t seem like it would be good practice to start a new session when a logged out user visits a page, but I don’t see a way around it.

You should use session_start on each entry point of your site. It’s needed to enable the session system.

You should definitly add userid, or some other data to the session on successful login and check this instead of just checking the session id as all users including guests should have a session id.

Reasons for guest having a session id could be many, you might want to track guests, you may have a shopping cart that they can add products to (would be annoying if it was reset on login), you may have posts/news they can get “marked as read”, etc etc.

Sponsor our Newsletter | Privacy Policy | Terms of Service