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:
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.
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";
}
}