<?php
namespace StorchakProject\framework\src;
use PDO;
use SessionHandlerInterface;
/**
* class SessionHandler
* writes sessions to the database
* @author Alexander Storchak <go280286sai@gmail.com>
*/
class SessionHandler implements SessionHandlerInterface
{
/**
* @var object|null
*/
private static object|null $instance = null;
/**
* @var false|pdo
*/
private pdo|bool $link;
private function __construct()
{
$this->link = new PDO('host', 'username', 'password');
}
public function __clone(): void
{
// TODO: Implement __clone() method.
}
/**
* @return object
*/
public static function getInstance(): object
{
if (self::$instance == null) {
return self::$instance = new self;
} else {
return self::$instance;
}
}
/**
* @param string $path
* @param string $name
* @return bool
*/
public function open(string $path, string $name): bool
{
if ($this->link) {
return true;
} else {
return false;
}
}
/**
* @return bool
*/
public function close(): bool
{
return true;
}
/**
* @param string $id
* @return false|mixed|string
*/
public function read(string $id): mixed
{
$sth = $this->link->query("SELECT * FROM Session WHERE Session_Id='$id'");
$rec = $sth->fetch();
if (!empty($rec)) {
return $rec['Session_Data'];
}
return '';
}
/**
* @param string $id
* @param string $data
* @return bool
*/
public function write(string $id, string $data): bool
{
$DateTime = date('Y-m-d H:i:s');
$NewDateTime = date('Y-m-d H:i:s', strtotime($DateTime . ' + 1 hour'));
$result = $this->link->query("REPLACE INTO Session SET Session_Id = '"
. $id . "', Session_Expires = '" . $NewDateTime . "', Session_Data = '" . $data . "'");
if ($result) {
return true;
} else {
return false;
}
}
/**
* @param string $id
* @return bool
*/
public function destroy(string $id): bool
{
$result = $this->link->query("DELETE FROM Session WHERE Session_Id ='" . $id . "'");
if ($result) {
return true;
} else {
return false;
}
}
/**
* @param int $max_lifetime
* @return bool
*/
public function gc(int $max_lifetime): bool
{
$result = $this->link->query("DELETE FROM Session WHERE ((UNIX_TIMESTAMP(Session_Expires) + "
. $max_lifetime . ") < " . $max_lifetime . ")");
if ($result) {
return true;
} else {
return false;
}
}
}
_______________________________________________________________________________