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

Session儲存到資料庫

WBOY
發布: 2016-07-25 09:09:01
原創
1036 人瀏覽過
  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 < time()){
  40. $this->destroy($id);
  41. return null;
  42. } else {
  43. return $result['data'];
  44. }
  45. }
  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 < ?';
  76. $stmt = $this->_pdo->prepare($sql);
  77. $stmt->execute(array(time() - $maxLifeTime));
  78. return true;
  79. }
  80. }
  81. try{
  82. $pdo = new PDO('mysql:host=localhost;dbname=rphp4zf', 'root','rickyfeng');
  83. $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  84. new SessionToDB($pdo);
  85. } catch(PDOException $e) {
  86. echo 'Error: '.$e->getMessage();
  87. }
复制代码


相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
最新問題
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板