I’m a beginner in php, and I am trying to create a login and logout. But I am having problems in logging out. My logout just calls for the login form which is this:
<?
session_start();
session_destroy();
?>
<table width="300" border="0" align="center" cellpadding="0" cellspacing="1" bgcolor="#CCCCCC">
<tr>
<form name="form1" method="post" action="checklogin.php">
<td>
<table width="100%" border="0" cellpadding="3" cellspacing="1" bgcolor="#FFFFFF">
<tr>
<td colspan="3"><strong>Member Login </strong></td>
</tr>
<tr>
<td width="78">Username</td>
<td width="6">:</td>
<td width="294"><input name="myusername" type="text" id="myusername"></td>
</tr>
<tr>
<td>Password</td>
<td>:</td>
<td><input name="mypassword" type="text" id="mypassword"></td>
</tr>
<tr>
<td> </td>
<td> </td>
<td><input type="submit" name="Submit" value="Login"></td>
</tr>
</table>
</td>
</form>
</tr>
</table>
My problem is, when I try to press the back button in the browser. Whoever user is using it can still access what is not supposed to be accessed when a user hasn’t logged in.
Do I need to add a code on the user page?
I have this code on the user page:
<?
session_start();
if(!session_is_registered(myusername)){
header("location:main_login.php");
}
?>
What can you recommend that I would do so that a script will prompt to enter the username and password again when a user clicks on the back button.
You’ve destroyed the session but are using a deprecated function,
session_is_registered(), to check whether the user is still authorised. As you can see here, you should not be using this any more.Instead when the user is authorized on the login page, set
$_SESSION['user'] = true. You could also set it to some data about that user. For example, I like to register as much information about the user as possible to prevent querying the database a large number of times in the future.Then this variable will be unset when you use session_destroy in your logout script. This means that in order to protect a page from a logged out user, you just need to include the following:
You should also protect your login page from logged in users so that they cannot login, whilst already being logged in:
This assumes you are using a query string on your login page to determine whether the user is trying to login or logout. If a logged in visitor wants to logout, they will have login.php?action=logout in their url and so will be allowed to logout. If not, they will be prevented from accessing the login page, as they have already logged in, and be sent straight to index.php (or wherever your protected section is).
If your login page is seperate from your logout page, you don’t need the $_GET condition at all.