PHP : Users getting logged out

Viewed 24

I have a custom written PHP application. Build 15 years ago. Working perfectly fine until recently when users reported they are being logged out even while they are actively using the application.

We use PHP sessions to manage users. The session expiry is set to 12 hours of inactivity. I reproduced the issue of being logged out. There is no pattern. at times I was logged out after 30 mins, at times 2 hours, at times 40 mins and so on. I captured the PHP session cookie and checked that the corresponding PHP session file existed in the tmp directory on the server. The session file was there on the server even when the application got me logged out and it was not even 2 hours (expiry set for 12 hours).

If I print the $_SESSION, this issue does not appear as much. Reproduced the issue in Chrome and Firefox. I have session_start and session_destroy only in logout service.

Any leads what could be causing this?

1 Answers

I faced same problem a few times. Workaround: use a "remember me" cookie for auto login.

Here's a recipe:

Whenever user logins successfully run this:

// remember me for a year every login
$login_string = hash('sha512', $user_id . $_SERVER['HTTP_USER_AGENT'] . time());
Project::update_table_record('users', $user_id, ["remember_me" => $login_string]);
$cookie_name = COOKIE_REMEMBER_ME;
$cookie_value = $login_string;
setcookie($cookie_name, $cookie_value, time() + (86400 * 365), "/"); // 365 day example

Whenever user chooses to logout, give him the option:

setcookie(COOKIE_REMEMBER_ME, "", time() - 3600, "/");

Otherwise, if no session then re-login if cookie is valid.

// auto login / remember me!
if (!LiveUser::get_id()) {

    if (isset($_COOKIE[COOKIE_REMEMBER_ME])) {
        $user_string = $_COOKIE[COOKIE_REMEMBER_ME];

        $user_id = Project::get_value('users', ['remember_me' => $user_string], 'id');
        if ($user_id) {
            Project::do_login($user_id);
        }
    }
}
Related