Reputation: 9075
Is there a way to close a PHP session without either writing or destroying it? Am I missing something or are there just two functions (session_write_close()
and session_destroy()
) which reset session_status()
to PHP_SESSION_NONE
? In other words, if I have an open session, can I simply close it without affecting the external session data, so it can be reloaded again.
Upvotes: 5
Views: 1548
Reputation: 9075
Some months later after raising an issue the two new methods are now available in PHP 5.6, but the documentation arrived only with 5.6.2.
session_abort()
– Discard session array changes and finish session, see the docs.session_reset()
– Re-initialize session array with original values, see the docs.Upvotes: 5
Reputation: 32280
You can do this by $_SESSION = null
. The session is unavailable but the data remains (does not get deleted).
Consider you have data in the session:
<?php
session_start();
session_regenerate_id(); // get a fresh id
echo session_id();
$_SESSION['test'] = '12345';
print_r($_SESSION); // echoes the data in the session
Data: test|s:5:"12345";
Then in the next request:
<?php
session_start();
echo session_id() . "<br>"; // echoes the same id as of the last request
$_SESSION = null;
print_r($_SESSION); // echoes nothing
echo "<br>";
echo session_status(); // echoes 2 (PHP_SESSION_ACTIVE)
Data still the same: test|s:5:"12345";
(php-fpm 5.4.29, most recent nginx, memcached as session handler
).
Well the data still can be written through $_SESSION['whatever'] = ...
but not read. I'm not sure whether this is a good solution but I have to admit I still don't understand why or whatfor you need this.
As an alternative, you could implement a wrapper class for the session with a property $this->active = true; // or false
:
class MySessionWrapper {
protected $active;
protected $data;
// getter setter for $this->active and $this->data ...
public function getData($var) {
if ($this->active !== true) {
throw new Exception('session disabled');
}
}
}
Upvotes: 3