2

I use the following codes to log users out from a web app. while logging in I set cookie email and password, but after logging out, visiting the home page automatically logs the user in again, probably because the cookie wasn't successfully destroyed. Please how do I get it right. Here is log out code

function log_out() {
   $old_user = $_SESSION['valid_user'];
   unset($_SESSION['valid_user']);
   unset($_SESSION['login']);
   unset($_SESSION['blog_addr']);
   $result_dest = session_destroy();

   setcookie('email', '');
   setcookie('pswd', '');

   if (!empty($old_user)) 
     if ($result_dest)
       return true;
     else 
       $msg = 'Could not log you out ';
   else 
        $msg = 'You have not been logged in so you are not logged out ';      
   return $msg;
}///:~
2

5 Answers 5

3

You need to set setcookie to an expiration date in the past. See the example here:

http://php.net/manual/en/function.setcookie.php

2

Try setting the cookie expiration for some time in the past:

setcookie ("email", "", time() - 3600);

1

How did you set up your cookie? ( logging in ).

In general setting a cookie off , you have to go back in time !

setcookie("email", "",time()-3600,'/');
1

In addition to other comments. You've set $_SESSION['valid_user']; to $old_user before you did an unset, so you should't be checking for $old_user as it contains the old data. you should't even need to set those to any variables. Also you should be using brackets.

function log_out() {
   unset($_SESSION['valid_user']);
   unset($_SESSION['login']);
   unset($_SESSION['blog_addr']);
   session_destroy();

   setcookie('email', '', time() - 3600);
   setcookie('pswd', '', time() - 3600);

   if (!isset($_SESSION['valid_user'])){
     if ($result_dest) // don't know what this does.
       return true;
     else 
       $msg = 'Could not log you out ';
   }
   else
        $msg = 'You have not been logged in so you are not logged out ';      
   return $msg;
}
1
  • 1
    I think the session_destroy() function returns a bool, so the line if($result_dest) checks if the session was successfully destroyed. although I don't really see need for that.
    – Chibuzo
    May 10, 2011 at 20:00
0

Try to delete the cookies by doing this:

setcookie ("email", "", time() - 3600);
setcookie ("pswd", "", time() - 3600);

This will delete the cookies by setting their expiration date in the past.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.