4 * This file is part of the Symfony package.
6 * (c) Fabien Potencier <fabien@symfony.com>
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
12 namespace Symfony\Component\HttpFoundation\Session\Storage;
14 use Symfony\Component\HttpFoundation\Session\SessionBagInterface;
15 use Symfony\Component\HttpFoundation\Session\Storage\Handler\StrictSessionHandler;
16 use Symfony\Component\HttpFoundation\Session\Storage\Proxy\AbstractProxy;
17 use Symfony\Component\HttpFoundation\Session\Storage\Proxy\SessionHandlerProxy;
20 * This provides a base class for session attribute storage.
22 * @author Drak <drak@zikula.org>
24 class NativeSessionStorage implements SessionStorageInterface
27 * @var SessionBagInterface[]
29 protected $bags = array();
34 protected $started = false;
39 protected $closed = false;
42 * @var AbstractProxy|\SessionHandlerInterface
44 protected $saveHandler;
49 protected $metadataBag;
52 * Depending on how you want the storage driver to behave you probably
53 * want to override this constructor entirely.
55 * List of options for $options array with their defaults.
57 * @see http://php.net/session.configuration for options
58 * but we omit 'session.' from the beginning of the keys for convenience.
60 * ("auto_start", is not supported as it tells PHP to start a session before
61 * PHP starts to execute user-land code. Setting during runtime has no effect).
63 * cache_limiter, "" (use "0" to prevent headers from being sent entirely).
67 * cookie_lifetime, "0"
73 * gc_maxlifetime, "1440"
75 * hash_bits_per_character, "4"
80 * serialize_handler, "php"
81 * use_strict_mode, "0"
83 * use_only_cookies, "1"
85 * upload_progress.enabled, "1"
86 * upload_progress.cleanup, "1"
87 * upload_progress.prefix, "upload_progress_"
88 * upload_progress.name, "PHP_SESSION_UPLOAD_PROGRESS"
89 * upload_progress.freq, "1%"
90 * upload_progress.min-freq, "1"
91 * url_rewriter.tags, "a=href,area=href,frame=src,form=,fieldset="
93 * sid_bits_per_character, "5"
94 * trans_sid_hosts, $_SERVER['HTTP_HOST']
95 * trans_sid_tags, "a=href,area=href,frame=src,form="
97 * @param array $options Session configuration options
98 * @param \SessionHandlerInterface|null $handler
99 * @param MetadataBag $metaBag MetadataBag
101 public function __construct(array $options = array(), $handler = null, MetadataBag $metaBag = null)
104 'cache_limiter' => '',
110 session_register_shutdown();
112 $this->setMetadataBag($metaBag);
113 $this->setOptions($options);
114 $this->setSaveHandler($handler);
118 * Gets the save handler instance.
120 * @return AbstractProxy|\SessionHandlerInterface
122 public function getSaveHandler()
124 return $this->saveHandler;
130 public function start()
132 if ($this->started) {
136 if (\PHP_SESSION_ACTIVE === session_status()) {
137 throw new \RuntimeException('Failed to start the session: already started by PHP.');
140 if (ini_get('session.use_cookies') && headers_sent($file, $line)) {
141 throw new \RuntimeException(sprintf('Failed to start the session because headers have already been sent by "%s" at line %d.', $file, $line));
144 // ok to try and start the session
145 if (!session_start()) {
146 throw new \RuntimeException('Failed to start the session');
149 $this->loadSession();
157 public function getId()
159 return $this->saveHandler->getId();
165 public function setId($id)
167 $this->saveHandler->setId($id);
173 public function getName()
175 return $this->saveHandler->getName();
181 public function setName($name)
183 $this->saveHandler->setName($name);
189 public function regenerate($destroy = false, $lifetime = null)
191 // Cannot regenerate the session ID for non-active sessions.
192 if (\PHP_SESSION_ACTIVE !== session_status()) {
196 if (headers_sent()) {
200 if (null !== $lifetime) {
201 ini_set('session.cookie_lifetime', $lifetime);
205 $this->metadataBag->stampNew();
208 $isRegenerated = session_regenerate_id($destroy);
210 // The reference to $_SESSION in session bags is lost in PHP7 and we need to re-create it.
211 // @see https://bugs.php.net/bug.php?id=70013
212 $this->loadSession();
214 return $isRegenerated;
220 public function save()
222 $session = $_SESSION;
224 foreach ($this->bags as $bag) {
225 if (empty($_SESSION[$key = $bag->getStorageKey()])) {
226 unset($_SESSION[$key]);
229 if (array($key = $this->metadataBag->getStorageKey()) === array_keys($_SESSION)) {
230 unset($_SESSION[$key]);
233 // Register error handler to add information about the current save handler
234 $previousHandler = set_error_handler(function ($type, $msg, $file, $line) use (&$previousHandler) {
235 if (E_WARNING === $type && 0 === strpos($msg, 'session_write_close():')) {
236 $handler = $this->saveHandler instanceof SessionHandlerProxy ? $this->saveHandler->getHandler() : $this->saveHandler;
237 $msg = sprintf('session_write_close(): Failed to write session data with "%s" handler', \get_class($handler));
240 return $previousHandler ? $previousHandler($type, $msg, $file, $line) : false;
244 session_write_close();
246 restore_error_handler();
247 $_SESSION = $session;
250 $this->closed = true;
251 $this->started = false;
257 public function clear()
259 // clear out the bags
260 foreach ($this->bags as $bag) {
264 // clear out the session
267 // reconnect the bags to the session
268 $this->loadSession();
274 public function registerBag(SessionBagInterface $bag)
276 if ($this->started) {
277 throw new \LogicException('Cannot register a bag when the session is already started.');
280 $this->bags[$bag->getName()] = $bag;
286 public function getBag($name)
288 if (!isset($this->bags[$name])) {
289 throw new \InvalidArgumentException(sprintf('The SessionBagInterface %s is not registered.', $name));
292 if (!$this->started && $this->saveHandler->isActive()) {
293 $this->loadSession();
294 } elseif (!$this->started) {
298 return $this->bags[$name];
301 public function setMetadataBag(MetadataBag $metaBag = null)
303 if (null === $metaBag) {
304 $metaBag = new MetadataBag();
307 $this->metadataBag = $metaBag;
311 * Gets the MetadataBag.
313 * @return MetadataBag
315 public function getMetadataBag()
317 return $this->metadataBag;
323 public function isStarted()
325 return $this->started;
329 * Sets session.* ini variables.
331 * For convenience we omit 'session.' from the beginning of the keys.
332 * Explicitly ignores other ini keys.
334 * @param array $options Session ini directives array(key => value)
336 * @see http://php.net/session.configuration
338 public function setOptions(array $options)
340 if (headers_sent() || \PHP_SESSION_ACTIVE === session_status()) {
344 $validOptions = array_flip(array(
345 'cache_expire', 'cache_limiter', 'cookie_domain', 'cookie_httponly',
346 'cookie_lifetime', 'cookie_path', 'cookie_secure',
347 'entropy_file', 'entropy_length', 'gc_divisor',
348 'gc_maxlifetime', 'gc_probability', 'hash_bits_per_character',
349 'hash_function', 'lazy_write', 'name', 'referer_check',
350 'serialize_handler', 'use_strict_mode', 'use_cookies',
351 'use_only_cookies', 'use_trans_sid', 'upload_progress.enabled',
352 'upload_progress.cleanup', 'upload_progress.prefix', 'upload_progress.name',
353 'upload_progress.freq', 'upload_progress.min_freq', 'url_rewriter.tags',
354 'sid_length', 'sid_bits_per_character', 'trans_sid_hosts', 'trans_sid_tags',
357 foreach ($options as $key => $value) {
358 if (isset($validOptions[$key])) {
359 ini_set('url_rewriter.tags' !== $key ? 'session.'.$key : $key, $value);
365 * Registers session save handler as a PHP session handler.
367 * To use internal PHP session save handlers, override this method using ini_set with
368 * session.save_handler and session.save_path e.g.
370 * ini_set('session.save_handler', 'files');
371 * ini_set('session.save_path', '/tmp');
373 * or pass in a \SessionHandler instance which configures session.save_handler in the
374 * constructor, for a template see NativeFileSessionHandler or use handlers in
375 * composer package drak/native-session
377 * @see http://php.net/session-set-save-handler
378 * @see http://php.net/sessionhandlerinterface
379 * @see http://php.net/sessionhandler
380 * @see http://github.com/drak/NativeSession
382 * @param \SessionHandlerInterface|null $saveHandler
384 * @throws \InvalidArgumentException
386 public function setSaveHandler($saveHandler = null)
388 if (!$saveHandler instanceof AbstractProxy &&
389 !$saveHandler instanceof \SessionHandlerInterface &&
390 null !== $saveHandler) {
391 throw new \InvalidArgumentException('Must be instance of AbstractProxy; implement \SessionHandlerInterface; or be null.');
394 // Wrap $saveHandler in proxy and prevent double wrapping of proxy
395 if (!$saveHandler instanceof AbstractProxy && $saveHandler instanceof \SessionHandlerInterface) {
396 $saveHandler = new SessionHandlerProxy($saveHandler);
397 } elseif (!$saveHandler instanceof AbstractProxy) {
398 $saveHandler = new SessionHandlerProxy(new StrictSessionHandler(new \SessionHandler()));
400 $this->saveHandler = $saveHandler;
402 if (headers_sent() || \PHP_SESSION_ACTIVE === session_status()) {
406 if ($this->saveHandler instanceof SessionHandlerProxy) {
407 session_set_save_handler($this->saveHandler, false);
412 * Load the session with attributes.
414 * After starting the session, PHP retrieves the session from whatever handlers
415 * are set to (either PHP's internal, or a custom save handler set with session_set_save_handler()).
416 * PHP takes the return value from the read() handler, unserializes it
417 * and populates $_SESSION with the result automatically.
419 protected function loadSession(array &$session = null)
421 if (null === $session) {
422 $session = &$_SESSION;
425 $bags = array_merge($this->bags, array($this->metadataBag));
427 foreach ($bags as $bag) {
428 $key = $bag->getStorageKey();
429 $session[$key] = isset($session[$key]) ? $session[$key] : array();
430 $bag->initialize($session[$key]);
433 $this->started = true;
434 $this->closed = false;