Link to home
Start Free TrialLog in
Avatar of Brad Bansner
Brad Bansner

asked on

Managing PHP sessions and timeouts

I am a beginning PHP programmer with a lot of Classic ASP experience. I am creating a new web app where users login and the login status is controlled with a PHP session. I have this bit of code inserted at the beginning of all my pages, via an include file:

session_start();

if (!isset($_SESSION["user_id"])){
	$user_login=0;
} else {
	if ($_SESSION["user_id"]==""){
		$user_login=0;
	} else {
		$user_login=1;
	}
}

Open in new window


For pages where I don't want non-logged in users to have access, I insert this at the top:

if ($user_login==0){
	header("Location: default.php", true, 303);
	die();
}

Open in new window


That simply bounces them back to the home (login) page if $user_login==0, rather than loading the rest of the page. If they are logged in ($user_login==1), then the page will load.

When the user clicks a "log out" button, I simply call this:

$_SESSION["user_id"]="";

Open in new window


All of that works fine. The odd thing is that my sessions don't seem to timeout. It is my understanding that a PHP session will timeout after 20 minutes of inactivity (similar to an ASP session). However, even after letting my browser window sit idle for over an hour, if I hit "reload", the browser does not redirect backt to the home (login) page.

Is there something I am missing? Also, is the way I am coding sessions in the above examples pretty solid, as far as PHP goes? Would appreciate any advice or critique on what I'm doing.

Thank you.
ASKER CERTIFIED SOLUTION
Avatar of Dave Baldwin
Dave Baldwin
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
When you want to end a session, please refer to the example code on this page.  http://php.net/manual/en/function.session-destroy.php
Avatar of Brad Bansner
Brad Bansner

ASKER

Thanks, this is very helpful, and it makes sense due to the way things have been working on this site.
You're welcome.  Sessions aren't all that hard but they are also not what most people expect at first.  The primary reason for sessions is to identify $_SESSION[] data to a particular user.  The timeout is really to clean up old data on the server.  That's why the timeout is not exact.