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