Created
February 26, 2015 16:03
-
-
Save dcb9/6280eaf5daa6a0c9cf1e to your computer and use it in GitHub Desktop.
用 MySQL 来记录 Session 数据实例
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 | |
ob_end_clean(); | |
if((int)ini_get('session.auto_start') > 0) | |
{ | |
ini_set('session.auto_start',0); | |
} | |
class MySqlSessionHandler implements SessionHandlerInterface | |
{ | |
private $_db; | |
public function close() | |
{ | |
return $this->_db->close(); | |
} | |
public function destroy($sessionn_id) | |
{ | |
$sql = 'delete from sessions where session_id="'.$session_id.'"'; | |
$this->_db->query($sql); | |
$_SESSION = array(); | |
return TRUE; | |
} | |
public function gc($maxlifetime) | |
{ | |
$sql = 'delete from sessions where expire < '.time(); | |
$zen_session_db->query($sql); | |
return TRUE; | |
} | |
public function open($save_path, $name) | |
{ | |
$this->_db = new mysqli('localhost','root','password','test'); | |
return (boolean)$this->_db; | |
} | |
public function read($session_id) | |
{ | |
$sql = 'select session_value from sessions where session_id="'.$session_id.'"'; | |
$query = $this->_db->query($sql); | |
if($this->_db->errno) { | |
die($this->_db->error); | |
} | |
if($query -> num_rows == 1) { | |
$session_data = $query->fetch_assoc(); | |
return $session_data['session_value']; | |
} else { | |
return ""; | |
} | |
} | |
public function write($session_id, $session_data) | |
{ | |
$sql = 'select count(*) as count from sessions where session_id="'.$session_id.'"'; | |
$query = $this->_db->query($sql); | |
$result = $query->fetch_assoc(); | |
if($this->_db->errno) { | |
die($this->_db->error); | |
} | |
if($result['count'] > 0) | |
{ | |
$sql = 'update sessions set session_value=\''.$session_data.'\',expire='.(time()+60*60).' where session_id="'. | |
$session_id.'"'; | |
$this->_db->query($sql); | |
} else { | |
$sql = 'insert into sessions values("'.$session_id.'","'.(time()+60*60).'",\''.$session_data.'\')'; | |
$this->_db->query($sql); | |
} | |
if($this->_db->affected_rows > 0) { | |
return TRUE; | |
} else { | |
return FALSE; | |
} | |
} | |
} | |
$handler = new MySqlSessionHandler; | |
session_set_save_handler($handler, true); | |
session_name('zenID'); | |
session_start(); | |
$_SESSION['age'] = 17; | |
$_SESSION['color'] = 'green'; | |
$_SESSION['color2'] = 'red'; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment