「PHPの学習」PHPでデータベースにセッションを保存するプログラム
PHPコード:
<?php
/*============================説明========================================
@filename: session.class.php
@description: データベースにオンラインユーザセッションを保存
@database: database:sessions field:sessionid(char32),uid(int10),last_visit(int10)
=============================================================================*/
class session {
private $db;
private $lasttime=3600;//タイムアウト:1時間
function session(&$db) {
$this->db = &$db;
session_module_name('user’); //sessionファイル保存方式
session_set_save_handler(
array(&$this, 'open’), //session_start()を実行
array(&$this, 'close’),
array(&$this, 'read’),
array(&$this, 'write’), //session_write_close()でsessionを強制終了
array(&$this, 'destroy’),
array(&$this, 'gc’)
);
session_start(); //session_set_save_handlerの後ろ実行
}
function unserializes($data_value) {
$vars = preg_split(
'/([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)\|/’,
$data_value, -1, PREG_SPLIT_NO_EMPTY |
PREG_SPLIT_DELIM_CAPTURE
);
for ($i = 0; isset($vars[$i]); $i++) {
$result[$vars[$i++]] = unserialize($vars[$i]);
}
return $result;
}
function open($path, $name) {
return true;
}
function close() {
$this->gc($this->lasttime);
return true;
}
function read($SessionKey){
$sql = “SELECT uid FROM sessions WHERE session_id = '".$SessionKey."' limit 1″;
$query =$this->db->query($sql);
if($row=$this->db->fetch_array($query)){
return $row['uid’];
}else{
return “";
}
}
function write($SessionKey,$VArray) {
require_once(MRoot.DIR_WS_CLASSES .’db_mysql_class.php’);
$db1=new DbCom();
// make a connection to the database… now
$db1->connect(DB_SERVER, DB_SERVER_USERNAME, DB_SERVER_PASSWORD, DB_DATABASE);
$db1->query(“set names utf8");
$this->db=$db1;
$SessionArray = addslashes($VArray);
$data=$this->unserializes($VArray);
$sql0 = “SELECT uid FROM sessions WHERE session_id = '".$SessionKey."' limit 1″;
$query0 =$this->db->query($sql0);
if($this->db->num_rows($query0)<=0){
if (isset($data['webid’]) && !empty($data['webid’])) {
$this->db->query(“insert into `sessions` set `session_id` = '$SessionKey’,uid='".$data['webid’]."',last_visit='".time()."'");
}
return true;
}else{
/*$sql = “update `sessions` set “;
if(isset($data['webid’])){
$sql .= “uid = '".$data['webid’]."', " ;
}
$sql.="`last_visit` = null "
. “where `session_id` = '$SessionKey'";
$this->db->query($sql); */
return true;
}
}
function destroy($SessionKey) {
$this->db->query(“delete from `sessions` where `session_id` = '$SessionKey'");
return true;
}
function gc($lifetime) {
$this->db->query(“delete from `sessions` where unix_timestamp(now()) -`last_visit` > '".$this->lasttime."'");
return true;
}
}
?>