NativeFileSessionHandler.php 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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. if (null === $savePath) {
  31. $savePath = \ini_get('session.save_path');
  32. }
  33. $baseDir = $savePath;
  34. if ($count = substr_count($savePath, ';')) {
  35. if ($count > 2) {
  36. throw new \InvalidArgumentException(sprintf('Invalid argument $savePath \'%s\'.', $savePath));
  37. }
  38. // characters after last ';' are the path
  39. $baseDir = ltrim(strrchr($savePath, ';'), ';');
  40. }
  41. if ($baseDir && !is_dir($baseDir) && !@mkdir($baseDir, 0777, true) && !is_dir($baseDir)) {
  42. throw new \RuntimeException(sprintf('Session Storage was not able to create directory "%s".', $baseDir));
  43. }
  44. if ($savePath !== \ini_get('session.save_path')) {
  45. ini_set('session.save_path', $savePath);
  46. }
  47. if ('files' !== \ini_get('session.save_handler')) {
  48. ini_set('session.save_handler', 'files');
  49. }
  50. }
  51. }