Miloš Đakonović
Miloš Đakonović

Reputation: 3871

How to 'unset' session save handler?

For some reason I have to initialize session with default save handler.

Previous code explicitly sets custom handler with session_set_save_handler().

Changing previous code is not a realistic option in my situation, so does anyone know how to restore handler to default eg is there session_restore_save_handler or session_unset_save_handler functions or equivalents?

Upvotes: 3

Views: 907

Answers (2)

kendsnyder
kendsnyder

Reputation: 783

As of PHP 5.4 you can revert to the default session handler by instantiating the SessionHandler class directly:

session_set_save_handler(new SessionHandler(), true);

Upvotes: 3

Miloš Đakonović
Miloš Đakonović

Reputation: 3871

Here I have to answer on my own question since no one said anything:

First, there is no session_restore_save_handler or session_unset_save_handler given from PHP and (by so far) no native way to get things back as they were before. For some reason, PHP team didn't give us option to juggle with session handlers in this way.

Second, native session mechanism can be emulated with following code

class FileSessionHandler
{
    private $savePath;

    function open($savePath, $sessionName)
    {
        $this->savePath = $savePath;
        if (!is_dir($this->savePath)) {
            mkdir($this->savePath, 0777);
        }

        return true;
    }

    function close()
    {
        return true;
    }

    function read($id)
    {
        return (string)@file_get_contents("$this->savePath/sess_$id");
    }

    function write($id, $data)
    {
        return file_put_contents("$this->savePath/sess_$id", $data) === false ? false : true;
    }

    function destroy($id)
    {
        $file = "$this->savePath/sess_$id";
        if (file_exists($file)) {
            unlink($file);
        }

        return true;
    }

    function gc($maxlifetime)
    {
        foreach (glob("$this->savePath/sess_*") as $file) {
            if (filemtime($file) + $maxlifetime < time() && file_exists($file)) {
                unlink($file);
            }
        }

        return true;
    }
}

$handler = new FileSessionHandler();
session_set_save_handler(
    array($handler, 'open'),
    array($handler, 'close'),
    array($handler, 'read'),
    array($handler, 'write'),
    array($handler, 'destroy'),
    array($handler, 'gc')
    );

register_shutdown_function('session_write_close');

This logic is closest to PHP's native session dealing one, but with , of course, unpredictable behavior in different circumstances. All I can right now conclude is that basic session operations is full covered with it.

Upvotes: 1

Related Questions