FileSessionHandler.php 2.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  1. <?php
  2. namespace Illuminate\Session;
  3. use SessionHandlerInterface;
  4. use Illuminate\Support\Carbon;
  5. use Symfony\Component\Finder\Finder;
  6. use Illuminate\Filesystem\Filesystem;
  7. class FileSessionHandler implements SessionHandlerInterface
  8. {
  9. /**
  10. * The filesystem instance.
  11. *
  12. * @var \Illuminate\Filesystem\Filesystem
  13. */
  14. protected $files;
  15. /**
  16. * The path where sessions should be stored.
  17. *
  18. * @var string
  19. */
  20. protected $path;
  21. /**
  22. * The number of minutes the session should be valid.
  23. *
  24. * @var int
  25. */
  26. protected $minutes;
  27. /**
  28. * Create a new file driven handler instance.
  29. *
  30. * @param \Illuminate\Filesystem\Filesystem $files
  31. * @param string $path
  32. * @param int $minutes
  33. * @return void
  34. */
  35. public function __construct(Filesystem $files, $path, $minutes)
  36. {
  37. $this->path = $path;
  38. $this->files = $files;
  39. $this->minutes = $minutes;
  40. }
  41. /**
  42. * {@inheritdoc}
  43. */
  44. public function open($savePath, $sessionName)
  45. {
  46. return true;
  47. }
  48. /**
  49. * {@inheritdoc}
  50. */
  51. public function close()
  52. {
  53. return true;
  54. }
  55. /**
  56. * {@inheritdoc}
  57. */
  58. public function read($sessionId)
  59. {
  60. if ($this->files->exists($path = $this->path.'/'.$sessionId)) {
  61. if (filemtime($path) >= Carbon::now()->subMinutes($this->minutes)->getTimestamp()) {
  62. return $this->files->get($path, true);
  63. }
  64. }
  65. return '';
  66. }
  67. /**
  68. * {@inheritdoc}
  69. */
  70. public function write($sessionId, $data)
  71. {
  72. $this->files->put($this->path.'/'.$sessionId, $data, true);
  73. return true;
  74. }
  75. /**
  76. * {@inheritdoc}
  77. */
  78. public function destroy($sessionId)
  79. {
  80. $this->files->delete($this->path.'/'.$sessionId);
  81. return true;
  82. }
  83. /**
  84. * {@inheritdoc}
  85. */
  86. public function gc($lifetime)
  87. {
  88. $files = Finder::create()
  89. ->in($this->path)
  90. ->files()
  91. ->ignoreDotFiles(true)
  92. ->date('<= now - '.$lifetime.' seconds');
  93. foreach ($files as $file) {
  94. $this->files->delete($file->getRealPath());
  95. }
  96. }
  97. }