php session expires randomly after a few minutes

2019-09-05 00:31发布

I have a login page/system which has worked correctly for years, leaving the user logged in until he/she either closes the browser window or logs out manually. But lately (starting yesterday) after only a few minutes of inactivity the session cookie/s seems to expire, causing the user to be logged out automatically.

This happens on different browsers and different operating systems, the PHP version is 5.6.29, which has been changed recently (before it was 5.5 and even 5.3).

I create and refresh the session on every page with session_start(). The login script first checks user name and PW and also gets some other user data from the database. These other data are first saved in variables and then written into session variables like

$_SESSION['username'] = $name;
$_SESSION['usertype'] = $type;

The successful login state is saved like this:

$_SESSION['login'] = "ok";

On the other pages I check the login state like this:

session_start();
if(($_SESSION['login'] != "ok") OR ($_SESSION['usertype'] != "xxx")) {
 header("Location: ../login.php"); /* redirects to login page if conditions are not true */
 exit;
 }

The login works, and logged-in users can proceed to other pages as long as the do it more or less in constant succession, but if someone waits a few minutes before proceding (i.e. without any acitivity), he/she is logged out (i.e. redirected to the login page when trying to open another page).

To make it extra-nasty, half of the time it just works as expected, also after half an hour...

Any help would be very much appreciated.


UPDATE:

Adding ini_set('session.gc_maxlifetime', 3600'); and `ini_set('session.cookie_lifetime', 3600); didn't help. I removed it again.

After that I had a look in the error logs and found this:

ap_pass_brigade failed with error 103: Software caused connection abort

(problem is, I don't have access to the server settings - this is on a shared webspace...)

2条回答
对你真心纯属浪费
2楼-- · 2019-09-05 01:02

You can see the php configuration (php.ini) by phpinfo();

<?php
phpinfo();

Check the session.gc_maxlifetime values first then if you need to set it see the following ways.

You can set it with .htaccess file if you don't have permission for edit the php.ini file.

.htaccess

<IfModule mod_php5.c>
    php_value session.cookie_lifetime 3600
    php_value session.gc_maxlifetime 3600
</IfModule>

Even you can set it by ini_set();

<?php
     ini_set('session.gc_maxlifetime', 3600);
查看更多
霸刀☆藐视天下
3楼-- · 2019-09-05 01:09

For anyone who is interested: The session didn't actually expire, but the session variables disappeared (and reappeared again randomly).

This is discussed in a follow-up question I posted here:

php $_SESSION variables disappear and reappear randomly

查看更多
登录 后发表回答