欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

php Session保存到数据库的类

程序员文章站 2022-05-17 15:35:30
...
  1. //用数据库保存session信息

  2. class SessionToDB
  3. {
  4. private $_path = null;
  5. private $_name = null;
  6. private $_pdo = null;
  7. private $_ip = null;
  8. private $_maxLifeTime = 0;
  9. public function __construct(PDO $pdo)

  10. {
  11. session_set_save_handler(
  12. array(&$this, 'open'),
  13. array(&$this, 'close'),
  14. array(&$this, 'read'),
  15. array(&$this, 'write'),
  16. array(&$this, 'destroy'),
  17. array(&$this, 'gc')
  18. );
  19. $this->_pdo = $pdo;

  20. $this->_ip = !empty($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : null;
  21. $this->_maxLifeTime = ini_get('session.gc_maxlifetime');
  22. }
  23. public function open($path,$name)

  24. {
  25. return true;
  26. }
  27. public function close()

  28. {
  29. return true;
  30. }
  31. public function read($id)

  32. {
  33. $sql = 'SELECT * FROM session where PHPSESSID = ?';
  34. $stmt = $this->_pdo->prepare($sql);
  35. $stmt->execute(array($id));
  36. if (!$result = $stmt->fetch(PDO::FETCH_ASSOC)) {

  37. return null;
  38. } elseif ($this->_ip != $result['client_ip']) {
  39. return null;
  40. } elseif ($result['update_time']+$this->_maxLifeTime $this->destroy($id);
  41. return null;
  42. } else {
  43. return $result['data'];
  44. }
  45. } //by bbs.it-home.org
  46. public function write($id,$data)

  47. {
  48. $sql = 'SELECT * FROM session where PHPSESSID = ?';
  49. $stmt = $this->_pdo->prepare($sql);
  50. $stmt->execute(array($id));
  51. if ($result = $stmt->fetch(PDO::FETCH_ASSOC)) {

  52. if ($result['data'] != $data) {
  53. $sql = 'UPDATE session SET update_time =? , date = ? WHERE PHPSESSID = ?';
  54. $stmt = $this->_pdo->prepare($sql);

  55. $stmt->execute(array(time(), $data, $id));
  56. }
  57. } else {
  58. if (!empty($data)) {
  59. $sql = 'INSERT INTO session (PHPSESSID, update_time, client_ip, data) VALUES (?,?,?,?)';
  60. $stmt = $this->_pdo->prepare($sql);
  61. $stmt->execute(array($id, time(), $this->_ip, $data));
  62. }
  63. }
  64. return true;

  65. }
  66. public function destroy($id)

  67. {
  68. $sql = 'DELETE FROM session WHERE PHPSESSID = ?';
  69. $stmt = $this->_pdo->prepare($sql);
  70. $stmt->execute(array($id));
  71. return true;

  72. }
  73. public function gc($maxLifeTime)

  74. {
  75. $sql = 'DELETE FROM session WHERE update_time $stmt = $this->_pdo->prepare($sql);
  76. $stmt->execute(array(time() - $maxLifeTime));
  77. return true;

  78. }
  79. }
  80. try{

  81. $pdo = new PDO('mysql:host=localhost;dbname=rphp4zf', 'root','rickyfeng');
  82. $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  83. new SessionToDB($pdo);

  84. } catch(PDOException $e) {
  85. echo 'Error: '.$e->getMessage();
  86. }
复制代码