首頁 >後端開發 >php教程 >php Session保存到資料庫的類

php Session保存到資料庫的類

WBOY
WBOY原創
2016-07-25 08:54:12934瀏覽
  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 < time()){
  41. $this->destroy($id);
  42. return null;
  43. } else {
  44. return $result['data'];
  45. }
  46. } //by bbs.it-home.org

  47. public function write($id,$data)

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

  52. if ($result = $stmt->fetch(PDO::FETCH_ASSOC)) {

  53. if ($result['data'] != $data) {
  54. $sql = 'UPDATE session SET update_time =? , date = ? WHERE PHPSESSID = ?';

  55. $stmt = $this->_pdo->prepare($sql);

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

  65. return true;

  66. }

  67. public function destroy($id)

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

  72. return true;

  73. }

  74. public function gc($maxLifeTime)

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

  79. return true;

  80. }
  81. }

  82. try{

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

  85. new SessionToDB($pdo);

  86. } catch(PDOException $e) {
  87. echo 'Error: '.$e->getMessage();
  88. }

复制代码


陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn