ホームページ  >  記事  >  バックエンド開発  >  phpセッションがデータベースに保存するクラス

phpセッションがデータベースに保存するクラス

WBOY
WBOYオリジナル
2016-07-25 08:54:12888ブラウズ
  1. //用データベース库保存セッション情報

  2. class SessionToDB
  3. {
  4. private $_path = null;
  5. プライベート $_name = null;
  6. プライベート $_pdo = null;
  7. プライベート $_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. パブリック関数 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. 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) {
  54. $sql = 'UPDATE セッション SET update_time =? 、日付 = ? 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. true を返します。

  66. }

  67. public function destroy($id)

  68. {
  69. $sql = 'セッションから削除 WHERE PHPSESSID = ?';
  70. $stmt = $this->_pdo->prepare($sql);
  71. $stmt->execute(array($id));

  72. return true;

  73. }

  74. パブリック関数 gc($maxLifeTime)

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

  78. return true;

  79. }
  80. }

  81. try{

  82. $pdo = 新しい 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 'エラー: '.$e->getMessage();
  87. }

复制代


声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。