Erik
Erik

Reputation: 137

PHP: determine session expiration

I have seen many articles on the internet but none of them answers my question. Which is a simple one. I want to solve this:

  1. user starts a form and a PHP session
  2. the user advances a few pages
  3. the user goes away for dinner and returns after a few hours
  4. the session has expired

I want to throw a message stating "your session has expired". However, a user that has never visited my site and starts the same form is now also presented the erroneous message because his session is also new.

I tried $_SERVER['HTTP_COOKIE'] which contains the sessionid. If that variable is set, I may assume the user tries to continue on that session (but it can no longer be retrieved). So when I start the session and it is empty, do I know then that he is an old friend, trying to reconnect?

Basic question: how can I make a distinction between a new user/session and a user that comes back after gc has removed its session file?

Thanks, Erik.

Upvotes: 0

Views: 30

Answers (1)

rover cj
rover cj

Reputation: 96

You could do that using a combination of $_SESSION and $_COOKIE.

<?php
session_start();

$cookieName = 'user_id';

//Check if the session has started 
//or not
if (isset($_SESSION['started'])) {
  // Session exists, proceed with 
  //normal operation
  echo "Welcome back!";
} else {
 // Session does not exist, check 
 //if the cookie is present
 if (isset($_COOKIE[$cookieName])) 
  {
    // Cookie exists but session 
    //does not, meaning the session 
    //has expired
    echo "Your session expired";
   } else {
    // No session and no cookie, 
    //it's a new user
    // Set a new session and a new 
    //cookie
    $_SESSION['started'] = true;
    $uniqueId = uniqid();
    //Generate a unique ID as you 
    //prefer
    setcookie($cookieName, 
      $uniqueId, time() + (86400 * 
       30),"/"); // 30 days expiry
    echo "New user";
   }
}

Upvotes: 1

Related Questions