phpsession

One problem in creating a PHP Session Authentication is that when you are logged in and suddenly logs out and click the back button you will be returned to the page where you kast visited.   Isn’t this a problem especially when you have important data in that page.  So if you have problem with this let me share a code that will surely eleminate the problem.  In this code there is no need for javascripts to disable the back button(what if js is disabled on the browser?).

The code uses session and when the user logs out the user is redirected to the login page and when he clicks the back button it will redirect back to the login page.  This is one trick for PHP Security Authentication.

#create a function to redirect the user to login page
#this should be on your php functions
function redirect($url){
	echo "<script type='text/javascript'>";
	echo "window.location.href='$url'";
	echo "</script>";
}

#this should be in your page where you authenticate the user
session_start();
$sql = mysql_query("select * from user
       where username=\"$username\" and userpassword=\"$password\"");

if(mysql_num_rows($sql) > 0) {
 $_SESSION['auth'] = true;
} else{
  redirect('login.php');
}

#so on the logout file there should be
session_destroy();
redirect('login.php');

Before starting in any of your PHP file you need to put this codes so that every now and the session is well monitored.

if( $_SESSION['auth'] == true) {

#PHP code here ...

} else{

redirect('login.php');
}

So in this code if the session is not true the user is redirected to the login page.  So when the user press that back button the user is always redirected to login page because the session created was destroyed.  I hope this code will help a lot especially those who just started their PHP programming.

Did find the post very useful? Maybe you want to buy me a glass of beer!