先看代码: <?php class CustomSession{ private $conn; public function __construct(){ session_set_save_handler( array($this, "open"), array($this, "close"), array($this, "read"), array($this, "write"), array($this, "destory"), array($this, "gc") ); } public function open($path, $id){ $this->conn = mysql_connect('localhost', 'root', '123456'); mysql_select_db("chapter3", $this->conn); } public function close(){ mysql_close($this->conn); } public function read($id){ $escaped_id = mysql_escape_string($id); $res = mysql_query("SELECT * FROM session WHERE session_id = '$escaped_id'", $this->conn); if($row = mysql_fetch_assoc($res)){ mysql_query("UPDATE session SET timestamp = " . time() . "WHERE session_id = '$escaped_id'", $this->conn); return $row['data']; } } public function write($id, $data){ $query = sprintf("REPLACE INTO session (session_id, data, timestamp) VALUES ('%s', '%s', '%s')", mysql_escape_string($id), mysql_escape_string($data), time()); $this->query($query); } public function destory($id){ $query = sprintf("DELETE FROM session WHERE session_id = '%s'", mysql_escape_string($id)); $res = mysql_query($query, $this->conn); return (mysql_affected_rows($res) == 1); } public function gc($lifetime){ $query = sprintf("DELETE FORM session WHERE %d - timestamp > %d", time(), $lifetime); mysql_query($query, $this->conn); } public function query($query){ $result = mysql_query($query, $this->conn); if(!$result){ die("Invalid Query: " . mysql_error($this->conn)); }else{ return $result; } } } ?> 注意:session_set_save_handler()要在session_start()之前调用,否则不起作用。