skip to Main Content

We need to make use of session_write_close() inside a lot of existing codes. But this looks dangerous to us, because PHP does the following – without giving any warning or error:

session_name('goodoldasdf');
session_start();

if (!empty($_SESSION['var'])) {
print ' Session-Data: '. $_SESSION['var'];
}

$_SESSION['var'] = "before";

session_write_close();

$_SESSION['var'] = "after"; // notice: definition after write close!

print ' B: '. $_SESSION['var'];

When we define a SESSION-var after session_write_close, PHP won’t write the SESSION into MemcacheD session handler (as expected) – but it still use the overwrite inside the same script runtime.

Output: ” Pseudo-Session-Data: after“.

second run:

Output: ” Session-Data: before Pseudo-Session-Data: after

The question is: How to make sure, that PHP is not using pseudo SESSION-vars, that are not actually written into the sessions? Is there a way to get PHP warnings here? Or any suggestions to handle this issue?


Why we need to add the write close everywhere: After updating “PHP 5.x” to “PHP 7” everything slows down. Notably on AJAX-requests or simultaneous loading mutli-tabs. It’s because PHP 7 seems to change it’s SESSION-handling / blocking.

Very good demo: https://demo.ma.ttias.be/demo-php-blocking-sessions/

So we need to add session_write_close to a lot of scripts – without risking invalid sessions-values.

2

Answers


  1. You can look at the output of session_status() (Docs)

    switch(session_status()) {
        case PHP_SESSION_DISABLED:
            die('Sessions disabled on this server');
        case PHP_SESSION_NONE:
            die('Session has not been started, or has been closed');
        case PHP_SESSION_ACTIVE:
            die('There is currently an active session');
    }
    

    You can utilise this with a wrapper function for getting / setting session variables.

    Login or Signup to reply.
  2. Instead of session_write_close(); write your own function and unset the superglobal:

    function session_stop() {
        session_write_close();
        unset($_SESSION);
    }
    

    Now you will get:

    Notice: Undefined variable: _SESSION in file X line Y

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search