Session保存到数据库

WBOY
发布: 2016-07-25 09:09:01
原创
1002 人浏览过
  1. class SessionToDB
  2. {
  3. private $_path = null;
  4. private $_name = null;
  5. private $_pdo = null;
  6. private $_ip = null;
  7. private $_maxLifeTime = 0;
  8. public function __construct(PDO $pdo)
  9. {
  10. session_set_save_handler(
  11. array(&$this, 'open'),
  12. array(&$this, 'close'),
  13. array(&$this, 'read'),
  14. array(&$this, 'write'),
  15. array(&$this, 'destroy'),
  16. array(&$this, 'gc')
  17. );
  18. $this->_pdo = $pdo;
  19. $this->_ip = !empty($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : null;
  20. $this->_maxLifeTime = ini_get('session.gc_maxlifetime');
  21. }
  22. public function open($path,$name)
  23. {
  24. return true;
  25. }
  26. public function close()
  27. {
  28. return true;
  29. }
  30. public function read($id)
  31. {
  32. $sql = 'SELECT * FROM session where PHPSESSID = ?';
  33. $stmt = $this->_pdo->prepare($sql);
  34. $stmt->execute(array($id));
  35. if (!$result = $stmt->fetch(PDO::FETCH_ASSOC)) {
  36. return null;
  37. } elseif ($this->_ip != $result['client_ip']) {
  38. return null;
  39. } elseif ($result['update_time']+$this->_maxLifeTime $this->destroy($id);
  40. return null;
  41. } else {
  42. return $result['data'];
  43. }
  44. }
  45. public function write($id,$data)
  46. {
  47. $sql = 'SELECT * FROM session where PHPSESSID = ?';
  48. $stmt = $this->_pdo->prepare($sql);
  49. $stmt->execute(array($id));
  50. if ($result = $stmt->fetch(PDO::FETCH_ASSOC)) {
  51. if ($result['data'] != $data) {
  52. $sql = 'UPDATE session SET update_time =? , date = ? WHERE PHPSESSID = ?';
  53. $stmt = $this->_pdo->prepare($sql);
  54. $stmt->execute(array(time(), $data, $id));
  55. }
  56. } else {
  57. if (!empty($data)) {
  58. $sql = 'INSERT INTO session (PHPSESSID, update_time, client_ip, data) VALUES (?,?,?,?)';
  59. $stmt = $this->_pdo->prepare($sql);
  60. $stmt->execute(array($id, time(), $this->_ip, $data));
  61. }
  62. }
  63. return true;
  64. }
  65. public function destroy($id)
  66. {
  67. $sql = 'DELETE FROM session WHERE PHPSESSID = ?';
  68. $stmt = $this->_pdo->prepare($sql);
  69. $stmt->execute(array($id));
  70. return true;
  71. }
  72. public function gc($maxLifeTime)
  73. {
  74. $sql = 'DELETE FROM session WHERE update_time $stmt = $this->_pdo->prepare($sql);
  75. $stmt->execute(array(time() - $maxLifeTime));
  76. return true;
  77. }
  78. }
  79. try{
  80. $pdo = new PDO('mysql:host=localhost;dbname=rphp4zf', 'root','rickyfeng');
  81. $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  82. new SessionToDB($pdo);
  83. } catch(PDOException $e) {
  84. echo 'Error: '.$e->getMessage();
  85. }
复制代码


相关标签:
来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!