NativeFileSessionHandler.php 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\HttpFoundation\Session\Storage\Handler;
  11. /**
  12. * Native session handler using PHP's built in file storage.
  13. *
  14. * @author Drak <drak@zikula.org>
  15. */
  16. class NativeFileSessionHandler extends \SessionHandler
  17. {
  18. /**
  19. * @param string|null $savePath Path of directory to save session files
  20. * Default null will leave setting as defined by PHP.
  21. * '/path', 'N;/path', or 'N;octal-mode;/path
  22. *
  23. * @see https://php.net/session.configuration#ini.session.save-path for further details.
  24. *
  25. * @throws \InvalidArgumentException On invalid $savePath
  26. * @throws \RuntimeException When failing to create the save directory
  27. */
  28. public function __construct(?string $savePath = null)
  29. {
  30. $baseDir = $savePath ??= \ini_get('session.save_path');
  31. if ($count = substr_count($savePath, ';')) {
  32. if ($count > 2) {
  33. throw new \InvalidArgumentException(sprintf('Invalid argument $savePath \'%s\'.', $savePath));
  34. }
  35. // characters after last ';' are the path
  36. $baseDir = ltrim(strrchr($savePath, ';'), ';');
  37. }
  38. if ($baseDir && !is_dir($baseDir) && !@mkdir($baseDir, 0777, true) && !is_dir($baseDir)) {
  39. throw new \RuntimeException(sprintf('Session Storage was not able to create directory "%s".', $baseDir));
  40. }
  41. if ($savePath !== \ini_get('session.save_path')) {
  42. ini_set('session.save_path', $savePath);
  43. }
  44. if ('files' !== \ini_get('session.save_handler')) {
  45. ini_set('session.save_handler', 'files');
  46. }
  47. }
  48. }