session.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: stanley-king
  5. * Date: 16/1/30
  6. * Time: 下午3:43
  7. */
  8. class session
  9. {
  10. static $stInstance = NULL;
  11. private $fdestroy = false;
  12. private $redis = NULL;
  13. private $enable = false;
  14. const type = 'redis';
  15. const save_path = 'tcp://127.0.0.1:6379';
  16. const prefix = 'PHPREDIS_SESSION';
  17. static public function instance()
  18. {
  19. if(self::$stInstance == NULL) {
  20. self::$stInstance = new session();
  21. }
  22. return self::$stInstance;
  23. }
  24. private function __construct()
  25. {
  26. $this->redis = new Redis;
  27. $this->enable = $this->redis->connect('127.0.0.1', 6379);
  28. }
  29. public function init()
  30. {
  31. @ini_set("session.save_handler", "redis");
  32. session_save_path(self::save_path);
  33. session_set_save_handler(
  34. array(&$this,'onOpen'),
  35. array(&$this,'onClose'),
  36. array(&$this,'onRead'),
  37. array(&$this,'onWrite'),
  38. array(&$this,'onDestroy'),
  39. array(&$this,'onGc'),
  40. array(&$this,'onCreateSid'));
  41. }
  42. public function start()
  43. {
  44. //会触发,open 和 read 函数
  45. session_start();
  46. }
  47. public function end()
  48. {
  49. // 会触发write 和 close 函数
  50. if($this->fdestroy == false) {
  51. session_write_close();
  52. }
  53. foreach($_SESSION as $key=>$value)
  54. {
  55. unset($_SESSION[$key]);
  56. }
  57. }
  58. public function destroy() {
  59. $this->fdestroy = true;
  60. session_destroy();//会触发destroy 和 close 函数
  61. }
  62. public function onOpen() {
  63. return true;
  64. }
  65. public function onRead($sid)
  66. {
  67. $ret = $this->redis->hGet(self::prefix,$sid);
  68. if(empty($ret)) {
  69. return '';
  70. } else {
  71. fcgi_header("Set-Cookie: PHPSESSID={$sid}");
  72. return $ret[0];
  73. }
  74. }
  75. public function onClose() {
  76. return true;
  77. }
  78. public function onWrite($sid, $data) {
  79. return $this->redis->hSet(self::prefix,$sid,$data);
  80. }
  81. public function onDestroy($sid) {
  82. return dcache($sid,self::prefix);
  83. }
  84. public function onGc($expire) {
  85. return true;
  86. }
  87. // public function onCreateSid()
  88. // {
  89. // $sid = 'vnk730je4l1c20cc479gpoesm6';
  90. //
  91. // return $sid;
  92. // }
  93. }