略微加速

PHP官方手册 - 互联网笔记

PHP - Manual: Sessions

2024-12-22

Session Handling

add a noteadd a note

User Contributed Notes 2 notes

up
5
e dot mortoray at ecircle dot com
13 years ago
There is a nuance we found with session timing out although the user is still active in the session.  The problem has to do with never modifying the session variable.

The GC will clear the session data files based on their last modification time.  Thus if you never modify the session, you simply read from it, then the GC will eventually clean up.

To prevent this you need to ensure that your session is modified within the GC delete time.  You can accomplish this like below.

<?php
if( !isset($_SESSION['last_access']) || (time() - $_SESSION['last_access']) > 60 )
 
$_SESSION['last_access'] = time();
?>

This will update the session every 60s to ensure that the modification date is altered.
up
-41
bouvrette dot nicolas at gmail dot com
7 years ago
Be careful if you are updating to PHP 5.6 since the the Sessions's Write behavior changed.  It now only writes the session if you changed the data. So this means that if you rely on your session to update an activity time stamp on the server (to control session expiry) you will end up having issues. Here is a quick fix if you are implementing SessionHandlerInterface:

    public function close() {
        $this->write($this->id, serialize($_SESSION));
        return true;
    }

Make sure you also use this:

        ini_set('session.serialize_handler', 'php_serialize'); // Force standard PHP functions handler for flexibility

More details here:

Request #17860 (Session write short circuit)
https://bugs.php.net/bug.php?id=17860

官方地址:https://www.php.net/manual/en/book.session.php

北京半月雨文化科技有限公司.版权所有 京ICP备12026184号-3