PHP logout not working

Hello. I have this php code that I am using to redirect users to index.html once the logout link is pressed but it’s not working.

Logout link in the navbar.

<li><a href="logout.php"> Logout </a></li>

Logout:

	       <?php
		session_start();
		session_unset();   
	        session_destroy();  
	        header('Location:index.html');
		?>

Also I have this session check on every page, and this redirecting is working:

  <?php
    session_start();
    if  (isset($_SESSION['session_user_first_name'])) 
      {
        if( isset($_SESSION[‘last_acted_on’]) && (time() - $_SESSION[‘last_acted_on’] > 60*5) )
          {
            session_unset();     // unset $_SESSION variable for the run-time
            session_destroy();   // destroy session data in storage
            header('Location: index.html');
          }
        else 
          {
            session_regenerate_id(true);
            $_SESSION[‘last_acted_on’] = time();
            include("header.html");
            include("menu.html");  
            require_once ('database_initialisation.php');
          }

    ?>

Any suggestions?

As stupid as it sounds: There’s a single character difference in these two lines… and it matters.

Use

unset($_SESSION['key']);

where “key” is index in $_SESSION you use to check is user logged in

I tried with the space and whiteout and still the same…

I tried unset($_SESSION[‘session_user_first_name’]); Still not working. The logout works correctly as it logs me out and I cant view pages until I login again, but it’s not redirecting the the index page.

if( isset($_SESSION[‘last_acted_on’]) && (time() - $_SESSION[‘last_acted_on’] > 60*5) )

These quotes look weird and different than the rest. Just an observation.

They should be single quotes, but I know it logs out the user after 5 minutes in this case. I tested it with 1 10 seconds :smiley:

Check that you have nothing before <?php (no tabs, no spaces, etc) and remove ?> to make sure there is nothing after it (closing php tag isn’t required if you have nothing after it).

1 Like

YESSS !! This worked, I put the <?php tag right at the beginning of my file. Thanks.

This is a very common problem. PHP can’t add header to the response if there was any output already. In your case symbols before <?php made that output.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.