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
You can look at the output of
session_status()
(Docs)You can utilise this with a wrapper function for getting / setting session variables.
Instead of
session_write_close();
write your own function and unset the superglobal:Now you will get: