php怎么把session保存到MySql数据库中

session我们多半是保存在服务器中,但是今天有一个功能就是需要把session保存在数据库中,这样可以实现同ie多浏览了,php中session默认的存储方式是硬盘,php也可以改变默认的存储方式,主要使用到session_set_save_handler方法,下面分享下如何将session保存到MySql数据库中的具体代码.

1.建session表,代码如下:

  1. CREATE TABLE `session` (
  2. `sessionid` varchar(128) NOT NULL,
  3. `uid` int(11) NOT NULL,
  4. `data` mediumblob NOT NULL,
  5. `timestamp` int(11) NOT NULL,
  6. `ip` varchar(15) NOT NULL,
  7. PRIMARY KEY (`sessionid`),
  8. KEY `time_session` (`timestamp`,`sessionid`)
  9. ) ENGINE=MyISAM DEFAULT CHARSET=utf8;
  10. //uid 是保留字段

2.自定义session类,代码如下:

  1. <?php
  2. class CustomSession{
  3. private static $db_host="localhost";
  4. private static $db_user="root";
  5. private static $db_password="";
  6. private static $database="session";
  7. private $conn;
  8. public static function getInstance(){
  9. static $instance=null;
  10. if($instance==null){
  11. $instance=new CustomSession();
  12. }
  13. return $instance;
  14. }
  15. public function __construct(){
  16. session_set_save_handler(
  17. array($this,"open"),
  18. array($this,"close"),
  19. array($this,"read"),
  20. array($this,"write"),
  21. array($this,"destroy"),
  22. array($this,"gc")
  23. );
  24. }
  25. public function __destruct(){
  26. session_write_close();
  27. }
  28. public function open(){
  29. $this->conn=mysql_connect(CustomSession::$db_host,CustomSession::$db_user,CustomSession::$db_password);
  30. mysql_select_db(CustomSession::$database,$this->conn);
  31. }
  32. public function close(){
  33. mysql_close($this->conn);
  34. }
  35. public function read($id){
  36. $escaped_id=mysql_escape_string($id);
  37. $res=$this->query("select * from `session` where `sessionid`='$escaped_id'");
  38. if($row=mysql_fetch_assoc($res)){
  39. $this->query("update `session` set `timetamp`=UTC_TIMESTAMP() where `sessionid`='$escaped_id'");
  40. return $row['data'];
  41. }
  42. return "";
  43. }
  44. public function write($id,$data){
  45. $query="replace into `session` (`sessionid`,`data`,`ip`,`timestamp`) values ('%s','%s','%s',UNIX_TIMESTAMP(UTC_TIMESTAMP()))";
  46. $this->query(sprintf($query,mysql_escape_string($id),mysql_escape_string($data),$_SERVER["REMOTE_ADDR"]));
  47. }
  48. public function destroy($id){
  49. $escaped_id=mysql_escape_string($id);
  50. $res=$this->query("delete from `session` where `id`='$escaped_id'");
  51. return (mysql_affected_rows($res)==1);
  52. }
  53. public function gc($lifetime){
  54. $this->query("delete from `session` where UNIX_TIMESTAMP(UTC_TIMESTAMP())-`timestamp` > $lifetime");
  55. }
  56. public function query($query){
  57. $res=mysql_query($query,$this->conn);
  58. return $res;
  59. }
  60. }
  61. ?>

3.测试程序,代码如下:

  1. <?php
  2. include('./CustomSession.class.php');
  3. CustomSession::getInstance();
  4. session_start();
  5. $_SESSION['username']='feng';
  6. print_r($_SESSION);
  7. ?>

运行测试程序后,查看数据库可以发现session表中已经增加了session记录.