Detect if Session expired

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
JayBird
Admin
Posts: 4524
Joined: Wed Aug 13, 2003 7:02 am
Location: York, UK
Contact:

Detect if Session expired

Post 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
User avatar
JayBird
Admin
Posts: 4524
Joined: Wed Aug 13, 2003 7:02 am
Location: York, UK
Contact:

Post 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
User avatar
liljester
Forum Contributor
Posts: 400
Joined: Tue May 20, 2003 4:49 pm

Post 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?
User avatar
JayBird
Admin
Posts: 4524
Joined: Wed Aug 13, 2003 7:02 am
Location: York, UK
Contact:

Post 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
User avatar
liljester
Forum Contributor
Posts: 400
Joined: Tue May 20, 2003 4:49 pm

Post 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?
Post Reply