Page 1 of 1

Detect if Session expired

Posted: Wed Jul 28, 2004 4:12 am
by JayBird
I have a simple login script just for testing purposes.

I have this at the top of all my protected pages

Code: Select all

session_start(); // Start/Resume session

if ( !$_SESSION['auth'] ) { 
   header("Location: /index.php"); 
}
Basically, when the user logs in $_SESSION['auth'] is set to true index.php is the login page they are redirected to if they aren't logged in and try to access a protected page.

Sessions timeout out after a certain perios of time set in the php.ini. What i want to do is detect if the session has timed out, so if it has, when the user is redirected back to the login page, they are also presented with a message along the lines of "For security reasons, you were automatically logged out".

Is this possible?

I am guessing i can't detect if the session has expired directly, but i could start a timer to detect the length of inactivity!?

Some pseudo code or point me in the direction fo the function i may need will do.

Thanks

Mark

Posted: Wed Jul 28, 2004 4:15 am
by JayBird
Sometimes typing it all out makes it clearer in my mind.

I just thought, when a user enters a page, i could store a timestamp in a session var, then on the next page, compare the stored timestamp with the current timestamp. If 10mins has elapsed, redirect them.

Is this a good method?

Mark

Posted: Wed Jul 28, 2004 9:14 am
by liljester
if the session times out, they are destroyed resulting in no session vars sent back to the browser... did your first script not work properly?

Posted: Wed Jul 28, 2004 9:16 am
by JayBird
liljester wrote:if the session times out, they are destroyed resulting in no session vars sent back to the browser... did your first script not work properly?
Yeah, i understand that, but how do i distiguish between someone that was logged in but their session has expired and someone that just hasn't logged in!?

Mark

Posted: Wed Jul 28, 2004 9:27 am
by liljester
ah =) then you where on the right track, use a timestamp in the db. =) you may have to use a cookie, and store their user_id or somesuch, so when they are redirected you can check the db to see if they actually logged out or just let the session expire... if they do log out, then mabe set the timestamp to 0 that way you know they didnt just let it expire?