PHP スーパーグローバル変数 $_SESSIONをDBで管理する


session_set_save_handler に指定のメソッドを作成したクラスを指定することで、独自に情報を管理できる。これによりPHPのセッションをDB上で管理することができる。

<?php
/*
MySQLのテーブルを作るクエリ
create table session (
  id char(32) primary key,
  updated datetime not null,
  data text
);
*/

class pdoSessionHandler implements SessionHandlerInterface {

	private $db;

	function __construct($connect) {
		$this->db=$connect;
	}
	
	function open($save_path, $name){
		return true;
	}
	
	function read($id){
		$pp=$this->db->prepare('select data from session where id=?');
		if($pp->execute([$id])){
			if($value=$pp->fetchColumn(0)){
				return $value;
			}
		}
		return '';
	}
	
	function write($id, $data){
		$pp=$this->db->prepare("replace into session values(?,now(),?)");
		return $pp->execute([$id, $data]);
	}
	
	function destroy($id){
		$pp=$this->db->prepare('delete from session where id=?');
		return $pp->execute($id);
	}
	
	function close(){
		return true;
	}
	
	function gc($expire){
		$pp=$this->db->prepare("delete from session where updated<date_add(now(),interval ? second)");
		return $pp->execute([$expire]);
	}
}

このクラスはコピペしてすぐに使えるのでご自由に。

<?php
 require('pdoSessionHandler.php');
 $db = new PDO( /*DB接続設定*/ );
 session_set_save_handler(new pdoSessionHandler($db), true);
 $_SESSION['hoge']='fuga';