ذخیره سشن در دیتابیس در PHP7 و بالاتر

ساخت وبلاگ

حالا باید کلاس مدیریت سشن خودمون رو بنویسیم. برای این کار باید کلاس ما حتماً رابط SessionHandlerInterface رو پیاده‌سازی کنه. کد این کلاس رو میگذارم:

class DbSessionHandler implements SessionHandlerInterface
{
   public $sessionTable = 'session_table';
   public $autoCreateSessionTable = true;
   public $expireTime = 1200; // in Seconds
   private function createTable()
   {
       DB::query('START TRANSACTION;');
       DB::query("
           CREATE TABLE `{$this->sessionTable}` (
             `id` char(32) NOT NULL,
             `data` longblob NOT NULL,
             `expire` int(11) NOT NULL
           ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
      ");
       DB::query("ALTER TABLE `{$this->sessionTable}` ADD PRIMARY KEY (`id`);");
       DB::query('COMMIT;');
   }
   private function deleteExpired()
   {
       return DB::query("DELETE FROM `{$this->sessionTable}` WHERE (`expire`<:expire)", [':expire' => time()]);
   }
   public function close()
   {
       return true;
   }
   public function destroy($session_id)
   {
       DB::query("DELETE FROM `{$this->sessionTable}` WHERE (`id`=:id)", [':id' => $session_id]);
       return true;
   }
   public function gc($maxlifetime)
   {
       $this->deleteExpired();
       return true;
   }
   public function open($save_path, $name)
   {
       if ($this->autoCreateSessionTable) {
           if ($this->deleteExpired() < 0) {
               $this->createTable();
           }
       }
       return true;
   }
   public function read($session_id)
   {
       $data = DB::arrayQuery("SELECT `data` FROM `{$this->sessionTable}` WHERE (`id`=:id AND `expire`>=:expire)", [':id' => $session_id, ':expire' => time()]);
       return (count($data) > 0 ? base64_decode($data[0]->data) : '');
   }
   public function write($session_id, $session_data)
   {
       return DB::query("REPLACE INTO `{$this->sessionTable}` VALUES (:id, :data, :expire)", [':id' => $session_id, ':data' => base64_encode($session_data), ':expire' => time() + $this->expireTime]) > 0;
   }
}

همونطور که میبینین، این کد خیلی شبیه کدی هست که قبلاً نوشتیم و نکته‌ی کلیدی قسمت implements SessionHandlerInterface هست و پیاده‌سازی متدهای close و destroy و gc و open و read و write هست.

برنامه نویس...
ما را در سایت برنامه نویس دنبال می کنید

برچسب : نویسنده : خنجی prog بازدید : 227 تاريخ : يکشنبه 8 تير 1399 ساعت: 3:19