Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

session timeout then redirect?

Status
Not open for further replies.

Hozzer

Technical User
Jul 30, 2009
20
CA
I'd like to redirect a page if the session times out, which is the best method to accomplish this?
Should it be done in the php.ini or the .htaccess file or using the php header(location) on each page?
 
Hi

You can not know when the session times out. There are two situations :
[ul]
[li]there is a valid session - PHP will provide it for your script[/li]
[li]there is no valid session - nothing[/li]
[/ul]
There is no difference between timed out, destroyed and never existing sessions.

For a simple example related to the use of session, see the recent thread434-1583410.

Feherke.
 
of course there is nothing to stop you setting a timestamp in the session and measuring that for timeouts. so long as the timeout value is shorter than the garbage collection interval.
 
Hi

Well, depends on what Hozzer means by "session".

I assumed the data handling mechanism provided by PHP. Which becomes unavailable when times out.

Of course, if he means "login session", then your answer is the suitable one. I just ignored that possibility because I find it pointless to put up theories about Hozzer's unspecified code and data.

Feherke.
 
I check for the valid session at the begining of my pages that should not be accessed if the session is not valid. If it is not set then I redirect to the login page.

Here is an example, though I am rather a noob at PHP programming:

Code:
<?php
session_start(); // start up your PHP session! 


if ($_SESSION[LoggedIn] != "True") 
{
   header("location:LoginPage.php");
   exit;
}
?>
 
do this

Code:
define('TIMEOUT', 60 * 60); // timeout of one hour
if ($_SESSION[LoggedIn] != "True" || $_SESSION['lastVisit'] + TIMEOUT < time()) 
{
   $_SESSION = array();
   $params = session_get_cookie_params();
    setcookie(session_name(), '', time() - 42000,
        $params["path"], $params["domain"],
        $params["secure"], $params["httponly"]
    );
   session_destroy();
   header("location:LoginPage.php");
   exit;
} else {
   $_SESSION['lastVisit'] = time();
}
 
i use the following code, on top of each of the pages i want the timout to run

$session_life = time() - $timeout;
if($session_life > $inactive)
{
session_destroy();
header("Location: Notpermitted.php");
}
$timeout=time();

Note that i have also created a variable called
$inactive which is set in seconds

whenever the time is over on this page, it destroys session.. however if they redirect to a new page, it changes the timeout variable

very simple (must have sessions active)
 
krappleby

your code is essentially identical to my post however i should point out a few differences:

1. php manual recommends expiring the session cookie as well as the session store. the method posted above is the approved version for session destruction as per the php manual.

2. you have not said how or where you set the $inactive variable. for this to be a valuable variable it needs to be stored in the session array itself. thus the variable should be $_SESSION['inactive']. for your code to work this variable needs to hold the number of seconds from 1st January 1970 until the user last logged in or visited a page.

3. it is unclear what you do with the $timeout variable after setting it equal to time(). you cannot store it in a session array as you have destroyed the session. what purpose does it serve? note that unless you issue an exit() command, the server code continues to execute. in this case it may be that you don't care because the user is no longer concerned with code execution in that script. however it is bad coding practice to do so (imo, at least).

4. i assume that if the session is valid you need to reset the $inactive variable (and store it in the session array). you have not shown this in the }else{ part of the if conditional.

5. it is good practice to issue an express exit or die command after header redirection. in other circumstances it is also useful to issue a session_write_close() command BEFORE the header redirection to avoid race conditions on the session store.
 
Hi

jpadie said:
it is good practice to issue an express exit or die command after header redirection.
I would say, that is not just good practice, it is mandatory. Otherwise the document will be generated and delivered. And with the help of NoRedirect the visitor will just continue to enjoy the navigation.

Feherke.
 
I apologize for the tardy reply to all of the helpful responses to my question. 'tis the season :)

I feel I should clarify my particular scecnario, essentially there would be no "loggedIn" session. This particular app will simply run and track interactivity from the user.
If for instance there is no user activity for 10 minutes then I assume the user has walked away from the terminal itself, I'd then like to redirect back to the home page of the app.
Of course 10 minutes is a long time but it's just a round number for the sake of this conservation.

On a windows platform there would be a default "timeout" set in the the web.config file which would fire every time there was no activity for "10 minutes", I'm just not as familiar with the apache / php approach to achieving the same result.

Thanks again for everyone's help. Between jpadie and krappleby's code examples I think I can work this out.
 
Hi

Hozzer said:
If for instance there is no user activity for 10 minutes then I assume the user has walked away from the terminal itself, I'd then like to redirect back to the home page of the app.
That sounds stupid. Why would you do that ? Why would that be useful for anybody ? The only logic reason I see is a public information terminal.

Anyway, after your last post seems that you only need this in every page's [tt]head[/tt] :
HTML:
[b]<meta[/b] [maroon]http-equiv[/maroon][teal]=[/teal][green][i]"refresh"[/i][/green] [maroon]content[/maroon][teal]=[/teal][green][i]"600; url=http://example.com/"[/i][/green][b]>[/b]

Feherke.
 
Hi Jpadie

please see my responses

1. php manual recommends expiring the session cookie as well as the session store. the method posted above is the approved version for session destruction as per the php manual.

yes. however i am not using cookies on this site, so just the session destroy is adequate. no need to make additional server load.


2. you have not said how or where you set the $inactive variable. for this to be a valuable variable it needs to be stored in the session array itself. thus the variable should be $_SESSION['inactive']. for your code to work this variable needs to hold the number of seconds from 1st January 1970 until the user last logged in or visited a page.

sorry. $inactive is set as a session variable, previously its set in seconds.. for the number of seconds that a user is permitted to be inactive before the script redirects them and destroys the session.


3. it is unclear what you do with the $timeout variable after setting it equal to time(). you cannot store it in a session array as you have destroyed the session. what purpose does it serve? note that unless you issue an exit() command, the server code continues to execute. in this case it may be that you don't care because the user is no longer concerned with code execution in that script. however it is bad coding practice to do so (imo, at least).

the timeout variable, resets to the current time when the page is loaded (note this is also a session variable, and carries through to all the pages. so as a new apge loads, the timout variable becomes the timeout variable of the next page..

4. i assume that if the session is valid you need to reset the $inactive variable (and store it in the session array). you have not shown this in the }else{ part of the if conditional.

inactive is set previously. it stays the same all the time.


----

basically what happens is the script knows that inactive is set for say 60 seconds..

when a page loads, it checks the time now - the last time timeout was updated, resulting in a number, if that number is greater than 60 or inactive, then the script destroys sessions..

PS.. i set sessions
via the
session_register() system

cheers
 
Just to add my $0.02, PHP is server side, so setting a session timeout will only work if the end-user tries to access another page.

Now you could use the http_equiv metta tag that would expire the page in xx seconds, but what if someone closes the browser?

You still need a mechanism to ensure that if that user starts that browser, or another browser, they cannot access the page.

I know I'm complicating this, but you should keep track of the browser and the IP address as well to ensure that the session cannot be started at another terminal or browser at the same time.

I do this on my web sites (paranoia) by using a small database with session logging information. Thus, each time a secured page is accessed, I can ensure that the user has permsiion to access that page(s).
 
Krappeleby said:
yes. however i am not using cookies on this site, so just the session destroy is adequate. no need to make additional server load.

i think it is unlikely that php is using transid to maintain session integrity. 95% certain that you are using cookies, you just don't know it. transid is very unreliable, particularly with redirects

Krappleby said:
sorry. $inactive is set as a session variable, previously its set in seconds.. for the number of seconds that a user is permitted to be inactive before the script redirects them and destroys the session.

given your code that will not work. in order for your code to work the variable must hold the unix timestamp of the last visit.

krappleby said:
the timeout variable, resets to the current time when the page is loaded (note this is also a session variable, and carries through to all the pages. so as a new apge loads, the timout variable becomes the timeout variable of the next page..

that will break your code. this line
Code:
$session_life = time() - $timeout;
will ALWAYS set $session_life to zero (or something mathmatically close to zero). if $timeout is the timestamp of the current visit of the page then this is also what is achieved from time(). so you are saying, in pseudo code:
krappleby said:
Code:
$session_life IS EQUAL TO current time MINUS time of script execution.

Krappleby said:
inactive is set previously. it stays the same all the time.

then your posted code will not work.

krappleby said:
when a page loads, it checks the time now - the last time timeout was updated, resulting in a number, if that number is greater than 60 or inactive, then the script destroys sessions..

fine. normal way of doing things and no different in net effect to the code posted by me on 17/12
jpadie said:
[/code]
$_SESSION['lastVisit'] + TIMEOUT < time()
[/code]
However the CODE THAT YOU POSTED DOES NOT DO THIS.

Krappleby said:
PS.. i set sessions
via the
session_register() system

somehow that does not surprise me. session_register() has been frowned upon for quite some time. deprecated since at least 5.3 and has been removed in php 5.6. The manual has long recommended setting session variables like so:

Code:
session_start(); //if required
$_SESSION['test'] = 'foobar';
 
bswip said:
PHP is server side, so setting a session timeout will only work if the end-user tries to access another page.
not necessarily. there are a number of ways to expire sessions without user interaction. for example you can control the garbage collection probability and the session timeout value. you could also run a database or file system cleanup on each page load, irrelevant of the incoming user. both methods are perfectly normal.

but you are right that session control server side does not cause a static page on a user's browser to expire. there are no good methods for this that I am aware of. javascript is the most obvious, but is easy to circumvent. I personally do not regard this as a major concern but for a bank, perhaps, i can see why it might. in their case i guess they deliver content via flash or java or require that javascript is turned on.

bswip said:
You still need a mechanism to ensure that if that user starts that browser, or another browser, they cannot access the page.

i think this depends on the application in question. i can think of many instances (pre-logged on e-commerce sites for example) where i would actively encourage session migration.

I am all in favour of database based sessions, coupled with decent authentication and authorisation layers. the only available app in PEAR is liveuser which I personally find opaque and unnecessarily heavyweight.
 
I agree, a database system is a great solution. I use this myself and find it very useful.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top