SessionHandler.php in Drupal 8
File
core/lib/Drupal/Core/Session/SessionHandler.php
View source
<?php
namespace Drupal\Core\Session;
use Drupal\Component\Utility\Crypt;
use Drupal\Core\Database\Connection;
use Drupal\Core\DependencyInjection\DependencySerializationTrait;
use Drupal\Core\Utility\Error;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpFoundation\Session\Storage\Proxy\AbstractProxy;
class SessionHandler extends AbstractProxy implements \SessionHandlerInterface {
use DependencySerializationTrait;
protected $requestStack;
protected $connection;
public function __construct(RequestStack $request_stack, Connection $connection) {
$this->requestStack = $request_stack;
$this->connection = $connection;
}
public function open($save_path, $name) {
return TRUE;
}
public function read($sid) {
$data = '';
if (!empty($sid)) {
$query = $this->connection
->queryRange('SELECT session FROM {sessions} WHERE sid = :sid', 0, 1, [
':sid' => Crypt::hashBase64($sid),
]);
$data = (string) $query
->fetchField();
}
return $data;
}
public function write($sid, $value) {
try {
$request = $this->requestStack
->getCurrentRequest();
$fields = [
'uid' => $request
->getSession()
->get('uid', 0),
'hostname' => $request
->getClientIP(),
'session' => $value,
'timestamp' => REQUEST_TIME,
];
$this->connection
->merge('sessions')
->keys([
'sid' => Crypt::hashBase64($sid),
])
->fields($fields)
->execute();
return TRUE;
} catch (\Exception $exception) {
require_once DRUPAL_ROOT . '/core/includes/errors.inc';
if (error_displayable()) {
print '<h1>Uncaught exception thrown in session handler.</h1>';
print '<p>' . Error::renderExceptionSafe($exception) . '</p><hr />';
}
return FALSE;
}
}
public function close() {
return TRUE;
}
public function destroy($sid) {
$this->connection
->delete('sessions')
->condition('sid', Crypt::hashBase64($sid))
->execute();
return TRUE;
}
public function gc($lifetime) {
$this->connection
->delete('sessions')
->condition('timestamp', REQUEST_TIME - $lifetime, '<')
->execute();
return TRUE;
}
}