Created
February 25, 2019 10:04
-
-
Save KaiserWerk/4553a7c20cb44c6d6775e699f8238a86 to your computer and use it in GitHub Desktop.
Store sessions in DB (using using catfan/medoo)
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
| CREATE TABLE IF NOT EXISTS sessions ( | |
| id varchar(32) NOT NULL, | |
| access int(10) unsigned DEFAULT NULL, | |
| data text, | |
| PRIMARY KEY (id) | |
| ) ENGINE=InnoDB DEFAULT CHARSET=latin1; |
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 | |
| class Session | |
| { | |
| private $db = false; | |
| public function __construct() | |
| { | |
| $this->db = new \Medoo\Medoo(); // http://medoo.in | |
| session_set_save_handler( | |
| [$this, "_open"], | |
| [$this, "_close"], | |
| [$this, "_read"], | |
| [$this, "_write"], | |
| [$this, "_destroy"], | |
| [$this, "_gc"] | |
| ); | |
| session_start(); // @? | |
| } | |
| public function _open() | |
| { | |
| if ($this->db !== false) { | |
| return true; | |
| } | |
| return false; | |
| } | |
| public function _close() | |
| { | |
| $this->db = null; | |
| return true; | |
| } | |
| public function _read($sessionID) | |
| { | |
| $row = $this->db->get('session', 'data', [ | |
| 'session_id' => $sessionID, | |
| ]); | |
| if ($row !== null) { | |
| return $row['data']; | |
| } | |
| return ''; | |
| } | |
| public function _write($sessionID, $data) | |
| { | |
| // Create time stamp | |
| $access = time(); | |
| $bool = $this->db->replace('session', [ | |
| 'access' => $access, | |
| 'data' => $data, | |
| ], [ | |
| 'session_id' => $sessionID, | |
| ]); | |
| if ($bool !== false) { | |
| return true; | |
| } | |
| return false; | |
| } | |
| public function _destroy($sessionID) | |
| { | |
| $bool = $this->db->delete('session', [ | |
| 'session_id' => $sessionID, | |
| ]); | |
| if($bool !== false) { | |
| return true; | |
| } | |
| return false; | |
| } | |
| public function _gc($max) | |
| { | |
| $old = time() - $max; | |
| $bool = $this->db->delete('session', [ | |
| 'access[<]' => $old, | |
| ]); | |
| if ($bool !== false) { | |
| return true; | |
| } | |
| return false; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment