Log users out

Hi. Trying my best to do something here with no success. At the top of my login page, I create a session

1 $_SESSION[‘loggedin’]=false;

Before any code is done, I do

1 if(!$_SESSION[‘loggedin’]){

To make sure the code is only run if loggedin == false.

in the login function, I set this session to true.

Now on my members page(once the users log in), before I run any code, I place it in

1 if($_SESSION[‘loggedin’]){

So this ensures that it will only run if the users have logged in.

This all works fine but it does not solve my initial problem. The user logs in using my form. If successful, they go to the members page. Here, they can now log out, which takes them back to the login page. Now in doing this, I was hoping the session loggedin was false. The reason why, at this point, I wanted to avoid the user being able to press the back button to get back to the members page. This doesnt work though. What else can i do?

cheers

the example on session_destroy() shows how to properly log out a user.

at logout unset and destroy the session var

don’t forget to start the session with session_start function in every php file

This is the problem. When the user logs in successfully, I do

 
$_SESSION['user']=$username;
		  
echo "<meta http-equiv=\\"Refresh\\" content=\\"0;url=page.php\\">";

This sets the session and takes them to the successful login page. On this page, I do

<p><?php
	echo "You are now logged in ".$_SESSION['user'] 
	?>
</p>
<a href= "login.php">Log Out 
<?php unset($_SESSION['user']); session_destroy() ?> 
</a>

This displays their login name and a log out button. Now if I click the log out button, I go back to the login page. But then if I click my browsers back button, it takes me to the successful login page, but just doesnt display the username. How do I restrict access to this page altogether once they are logged out?

cheers

First, when a user logs in, the authentication script sets a session variable, say for example

 
$_SESSION['sessVar'] = 'someHardToGuessValue';

then on top of every sessioned page you could have something similar to this

 
<?php
session_start();
 
if(!isset($_SESSION['sessVar']) || $_SESSION['sessVar'] != 'someHardToGuessValue') {
      die('You are not an authorised user');
}
 

You’re calling unset() and session_destroy() when you print the log out link to the page, so just showing the log out link is logging them out! You need to make the link direct to a script that will log them out, not print it within the link :slight_smile: