Skip to content

Instantly share code, notes, and snippets.

@DanyHenriquez
Created May 12, 2016 20:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DanyHenriquez/ea08d9ced419fe48ef690ab462857661 to your computer and use it in GitHub Desktop.
Save DanyHenriquez/ea08d9ced419fe48ef690ab462857661 to your computer and use it in GitHub Desktop.
Php7 MongoDB session handler.
<?php
class MongoSessionHandler implements \SessionHandlerInterface
{
public $client;
public $database;
public $collection;
public function __construct($uri, $uriOptions = [], $driverOptions = [])
{
$this->client = new \MongoDB\Client($uri, $uriOptions, $driverOptions);
}
public function withDatabase($database)
{
$new = clone $this;
$new->database = $database;
return $new;
}
public function withCollection($collection)
{
$new = clone $this;
$new->collection = $collection;
return $new;
}
public function open($savePath, $sessionName)
{
return true;
}
public function close()
{
return true;
}
public function read($id)
{
return $this
->client
->{$this->database}
->{$this->collection}
->findOne(['sessionId' => $id])
->data;
}
public function write($id, $data)
{
$this->destroy($id);
$this
->client
->{$this->database}
->{$this->collection}
->insertOne(['sessionId' => $id, 'data' => $data, 'createdAt' => time()]);
return true;
}
public function destroy($id)
{
$this
->client
->{$this->database}
->{$this->collection}
->deleteOne(['sessionId' => $id]);
return true;
}
public function gc($maxlifetime)
{
foreach ($this->client->{$this->database}->{$this->collection}->find() as $session) {
if ($session->createdAt + $maxlifetime < time()) {
$this
->client
->{$this->database}
->{$this->collection}
->deleteOne(['sessionId' => $session->sessionId]);
}
}
return true;
}
}
<?php
$sessionHandler = (new \System\MongoSessionHandler('mongodb://localhost:27017'))
->withDatabase('session')
->withCollection('session');
session_set_save_handler($sessionHandler, true);
session_start();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment