keewee279
keewee279

Reputation: 1654

PHP: How to prevent session from expiring while user is still logged in

I am new to PHP and hope someone can help me with this.

I currently use the following to create a session / cookie and to redirect the user to a login page if the session is expired or he is not logged in. This is included on all pages of a website.

So far this seems to work as intended. However, when I tested this with a short lifetime (e.g. 2 minutes) it also redirected me to the login page while I was still on the site and logged in.

Is there a way I can set this to not expire as long as the user is on the site resp. as long as the site is open in the browser ? I did some research but couldn't find any proper tutorial for this.

My PHP:

session_set_cookie_params(86400 * 30, "/");
if(isset($_COOKIE["PHPSESSID"])){
    session_id($_COOKIE["PHPSESSID"]);
}

session_start();

$pageURL = basename($_SERVER["REQUEST_URI"]);
$pageName = pathinfo(parse_url($pageURL, PHP_URL_PATH), PATHINFO_FILENAME); 

if( (!isset($_SESSION["user"]["status"])) && ($pageName != "login") ){
    header("Location: " . $baseURL . "/login.php");
    exit;
}

Many thanks for any help with this, Mike

Upvotes: 0

Views: 2945

Answers (1)

Skarlinski
Skarlinski

Reputation: 2469

The user must browse to a page on the site in order to preserve the session.

A possible solution will be to use timed ajax calls to keep the session alive.

Every time a user sends an http request to your site, the cookie containing the session data is sent alongside and server extends the session.

Example of adding ajax call to refresh session. Add script after jquery is loaded. Will send an ajax call to your domain root every 60 seconds.

setTimeout(function(){
     $.get({url:'/'})
 }, 60 * 1000);

Using ajax to preserve session is kind of hackish and could lead to many problems later. Use With caution!

Upvotes: 2

Related Questions