Created
November 12, 2020 17:26
-
-
Save BlackScorp/4ae8f1c199410a7a9d3f9c398535dcf0 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
error_reporting(E_ALL); | |
ini_set('display_errors','On'); | |
class MysqlSessionHandler implements SessionHandlerInterface,SessionIdInterface{ | |
private PDO $pdo; | |
private PDOStatement $readStatement; | |
private PDOStatement $writeStatement; | |
public function __construct(PDO $pdo){ | |
$this->pdo = $pdo; | |
} | |
private function getNextFreeId(){ | |
$id = md5(microtime(true)); | |
$this->readStatement->execute([':sessionId'=>$id]); | |
if($this->readStatement->rowCount() > 0){ | |
$id = $this->getNextFreeId(); | |
} | |
return $id; | |
} | |
public function create_sid(){ | |
return $this->getNextFreeId(); | |
} | |
public function close(){ | |
return true; | |
} | |
public function open($savePath, $sessionName) | |
{ | |
$sql ="SELECT value FROM sessions WHERE id=:sessionId"; | |
$this->readStatement = $this->pdo->prepare($sql); | |
$sql ="INSERT INTO sessions SET value=:value,id=:sessionId ON DUPLICATE KEY UPDATE value=:value"; | |
$this->writeStatement = $this->pdo->prepare($sql); | |
return true; | |
} | |
public function read($id) | |
{ | |
$this->readStatement->execute([':sessionId'=>$id]); | |
return (string) $this->readStatement->fetchColumn(); | |
} | |
public function write($id,$data){ | |
$result = $this->writeStatement->execute([ | |
':value'=>$data, | |
':sessionId'=>$id | |
]); | |
return $result; | |
} | |
public function destroy($id){ | |
$deleteSQL = "DELETE FROM sessions WHERE id=:sessionId"; | |
$statement = $this->pdo->prepare($deleteSQL); | |
$result= $statement->execute([':sessionId'=>$id]); | |
return $result; | |
} | |
public function gc($maxlifetime){ | |
$cleanUpSQL ="DELETE FROM sessions WHERE NOW() > DATE_ADD(lastUpdate,INTERVAL ".(int)$maxlifetime." SECOND)"; | |
return $this->pdo->exec($cleanUpSQL); | |
} | |
} | |
$pdo = new PDO('mysql:host=localhost;dbname=test;charset=utf8mb4','root',''); | |
$sessionHandler = new MysqlSessionHandler($pdo); | |
session_set_save_handler($sessionHandler,true); | |
session_start(); | |
$_SESSION['test'] = 'foo'; | |
$_SESSION['test2'] = [ | |
'test' | |
]; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment