views:

106

answers:

3

I'm having difficulties in the making the logout code for php to work. When I click on the logout button, it will go back to the home page, but when I click on the back button in the browser. I can still access the previous page, wherein the user must be logged on to access it. So I'm thinking of redirecting to the login page when the user clicks on the back button on the browser.

This is my code, in the home page(where in no user is logged in yet. This page is being called by a logout link on the user page.

   <?
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>&nbsp;</td>
<td>&nbsp;</td>
<td><input type="submit" name="Submit" value="Login"></td>
</tr>
</table>
</td>
</form>
</tr>
</table>
+2  A: 
<?php header('Location:'. $myurl);exit;?>

Should do the trick to redirect assuming nothing has been sent to the browser.

But your problem is more about checking if the user have the right credential for this page. After the session_start(), you should check if a user is present in the session. For example when the user logging, put something in the session to identify your user:

<?php $_SESSION['user_id'] = $userid; ?>

When you want to access any page which requires a user to be logged:

<?php if (empty($_SESSION['user_id)) { header('Location: /');exit;} ?>

so if the user_id is not present in the session, you user is not logged, thus redirect him to the homepage.

You should also not destroy the session after creating it. Destroying the session should only been done when the user sign out. but session start should be done all the time (just easier that way)

stunti
A: 

In your sign out page just unset $_SESSION['user_id'] before you can redirect it to the home page.

unset($_SESSIOM['user_id']);

Then in all other pages which requires user to login first just check if the user_id for the session is set if its not set just redirect them back to the home page, just like stunti told in above comment

Vasudev
A: 

The spaces before the script start will break the "Location" method proposed by stunti.

   <?
^^^

Be careful and remove them.

fjfnaranjo