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\NativeSessionHandler;
16 use Symfony\Component\HttpFoundation\Session\Storage\Proxy\NativeProxy;
17 use Symfony\Component\HttpFoundation\Session\Storage\Proxy\AbstractProxy;
18 use Symfony\Component\HttpFoundation\Session\Storage\Proxy\SessionHandlerProxy;
21 * This provides a base class for session attribute storage.
23 * @author Drak <drak@zikula.org>
25 class NativeSessionStorage implements SessionStorageInterface
28 * Array of SessionBagInterface.
30 * @var SessionBagInterface[]
37 protected $started = false;
42 protected $closed = false;
47 protected $saveHandler;
52 protected $metadataBag;
57 * Depending on how you want the storage driver to behave you probably
58 * want to override this constructor entirely.
60 * List of options for $options array with their defaults.
62 * @see http://php.net/session.configuration for options
63 * but we omit 'session.' from the beginning of the keys for convenience.
65 * ("auto_start", is not supported as it tells PHP to start a session before
66 * PHP starts to execute user-land code. Setting during runtime has no effect).
68 * cache_limiter, "" (use "0" to prevent headers from being sent entirely).
71 * cookie_lifetime, "0"
77 * gc_maxlifetime, "1440"
79 * hash_bits_per_character, "4"
83 * serialize_handler, "php"
85 * use_only_cookies, "1"
87 * upload_progress.enabled, "1"
88 * upload_progress.cleanup, "1"
89 * upload_progress.prefix, "upload_progress_"
90 * upload_progress.name, "PHP_SESSION_UPLOAD_PROGRESS"
91 * upload_progress.freq, "1%"
92 * upload_progress.min-freq, "1"
93 * url_rewriter.tags, "a=href,area=href,frame=src,form=,fieldset="
95 * @param array $options Session configuration options
96 * @param AbstractProxy|NativeSessionHandler|\SessionHandlerInterface|null $handler
97 * @param MetadataBag $metaBag MetadataBag
99 public function __construct(array $options = array(), $handler = null, MetadataBag $metaBag = null)
101 session_cache_limiter(''); // disable by default because it's managed by HeaderBag (if used)
102 ini_set('session.use_cookies', 1);
104 session_register_shutdown();
106 $this->setMetadataBag($metaBag);
107 $this->setOptions($options);
108 $this->setSaveHandler($handler);
112 * Gets the save handler instance.
114 * @return AbstractProxy
116 public function getSaveHandler()
118 return $this->saveHandler;
124 public function start()
126 if ($this->started) {
130 if (PHP_VERSION_ID >= 50400 && \PHP_SESSION_ACTIVE === session_status()) {
131 throw new \RuntimeException('Failed to start the session: already started by PHP.');
134 if (PHP_VERSION_ID < 50400 && !$this->closed && isset($_SESSION) && session_id()) {
135 // not 100% fool-proof, but is the most reliable way to determine if a session is active in PHP 5.3
136 throw new \RuntimeException('Failed to start the session: already started by PHP ($_SESSION is set).');
139 if (ini_get('session.use_cookies') && headers_sent($file, $line)) {
140 throw new \RuntimeException(sprintf('Failed to start the session because headers have already been sent by "%s" at line %d.', $file, $line));
143 // ok to try and start the session
144 if (!session_start()) {
145 throw new \RuntimeException('Failed to start the session');
148 $this->loadSession();
149 if (!$this->saveHandler->isWrapper() && !$this->saveHandler->isSessionHandlerInterface()) {
150 // This condition matches only PHP 5.3 with internal save handlers
151 $this->saveHandler->setActive(true);
160 public function getId()
162 return $this->saveHandler->getId();
168 public function setId($id)
170 $this->saveHandler->setId($id);
176 public function getName()
178 return $this->saveHandler->getName();
184 public function setName($name)
186 $this->saveHandler->setName($name);
192 public function regenerate($destroy = false, $lifetime = null)
194 // Cannot regenerate the session ID for non-active sessions.
195 if (PHP_VERSION_ID >= 50400 && \PHP_SESSION_ACTIVE !== session_status()) {
199 // Check if session ID exists in PHP 5.3
200 if (PHP_VERSION_ID < 50400 && '' === session_id()) {
204 if (null !== $lifetime) {
205 ini_set('session.cookie_lifetime', $lifetime);
209 $this->metadataBag->stampNew();
212 $isRegenerated = session_regenerate_id($destroy);
214 // The reference to $_SESSION in session bags is lost in PHP7 and we need to re-create it.
215 // @see https://bugs.php.net/bug.php?id=70013
216 $this->loadSession();
218 return $isRegenerated;
224 public function save()
226 session_write_close();
228 if (!$this->saveHandler->isWrapper() && !$this->saveHandler->isSessionHandlerInterface()) {
229 // This condition matches only PHP 5.3 with internal save handlers
230 $this->saveHandler->setActive(false);
233 $this->closed = true;
234 $this->started = false;
240 public function clear()
242 // clear out the bags
243 foreach ($this->bags as $bag) {
247 // clear out the session
250 // reconnect the bags to the session
251 $this->loadSession();
257 public function registerBag(SessionBagInterface $bag)
259 if ($this->started) {
260 throw new \LogicException('Cannot register a bag when the session is already started.');
263 $this->bags[$bag->getName()] = $bag;
269 public function getBag($name)
271 if (!isset($this->bags[$name])) {
272 throw new \InvalidArgumentException(sprintf('The SessionBagInterface %s is not registered.', $name));
275 if ($this->saveHandler->isActive() && !$this->started) {
276 $this->loadSession();
277 } elseif (!$this->started) {
281 return $this->bags[$name];
285 * Sets the MetadataBag.
287 * @param MetadataBag $metaBag
289 public function setMetadataBag(MetadataBag $metaBag = null)
291 if (null === $metaBag) {
292 $metaBag = new MetadataBag();
295 $this->metadataBag = $metaBag;
299 * Gets the MetadataBag.
301 * @return MetadataBag
303 public function getMetadataBag()
305 return $this->metadataBag;
311 public function isStarted()
313 return $this->started;
317 * Sets session.* ini variables.
319 * For convenience we omit 'session.' from the beginning of the keys.
320 * Explicitly ignores other ini keys.
322 * @param array $options Session ini directives array(key => value)
324 * @see http://php.net/session.configuration
326 public function setOptions(array $options)
328 $validOptions = array_flip(array(
329 'cache_limiter', 'cookie_domain', 'cookie_httponly',
330 'cookie_lifetime', 'cookie_path', 'cookie_secure',
331 'entropy_file', 'entropy_length', 'gc_divisor',
332 'gc_maxlifetime', 'gc_probability', 'hash_bits_per_character',
333 'hash_function', 'name', 'referer_check',
334 'serialize_handler', 'use_cookies',
335 'use_only_cookies', 'use_trans_sid', 'upload_progress.enabled',
336 'upload_progress.cleanup', 'upload_progress.prefix', 'upload_progress.name',
337 'upload_progress.freq', 'upload_progress.min-freq', 'url_rewriter.tags',
340 foreach ($options as $key => $value) {
341 if (isset($validOptions[$key])) {
342 ini_set('session.'.$key, $value);
348 * Registers session save handler as a PHP session handler.
350 * To use internal PHP session save handlers, override this method using ini_set with
351 * session.save_handler and session.save_path e.g.
353 * ini_set('session.save_handler', 'files');
354 * ini_set('session.save_path', '/tmp');
356 * or pass in a NativeSessionHandler instance which configures session.save_handler in the
357 * constructor, for a template see NativeFileSessionHandler or use handlers in
358 * composer package drak/native-session
360 * @see http://php.net/session-set-save-handler
361 * @see http://php.net/sessionhandlerinterface
362 * @see http://php.net/sessionhandler
363 * @see http://github.com/drak/NativeSession
365 * @param AbstractProxy|NativeSessionHandler|\SessionHandlerInterface|null $saveHandler
367 * @throws \InvalidArgumentException
369 public function setSaveHandler($saveHandler = null)
371 if (!$saveHandler instanceof AbstractProxy &&
372 !$saveHandler instanceof NativeSessionHandler &&
373 !$saveHandler instanceof \SessionHandlerInterface &&
374 null !== $saveHandler) {
375 throw new \InvalidArgumentException('Must be instance of AbstractProxy or NativeSessionHandler; implement \SessionHandlerInterface; or be null.');
378 // Wrap $saveHandler in proxy and prevent double wrapping of proxy
379 if (!$saveHandler instanceof AbstractProxy && $saveHandler instanceof \SessionHandlerInterface) {
380 $saveHandler = new SessionHandlerProxy($saveHandler);
381 } elseif (!$saveHandler instanceof AbstractProxy) {
382 $saveHandler = PHP_VERSION_ID >= 50400 ?
383 new SessionHandlerProxy(new \SessionHandler()) : new NativeProxy();
385 $this->saveHandler = $saveHandler;
387 if ($this->saveHandler instanceof \SessionHandlerInterface) {
388 if (PHP_VERSION_ID >= 50400) {
389 session_set_save_handler($this->saveHandler, false);
391 session_set_save_handler(
392 array($this->saveHandler, 'open'),
393 array($this->saveHandler, 'close'),
394 array($this->saveHandler, 'read'),
395 array($this->saveHandler, 'write'),
396 array($this->saveHandler, 'destroy'),
397 array($this->saveHandler, 'gc')
404 * Load the session with attributes.
406 * After starting the session, PHP retrieves the session from whatever handlers
407 * are set to (either PHP's internal, or a custom save handler set with session_set_save_handler()).
408 * PHP takes the return value from the read() handler, unserializes it
409 * and populates $_SESSION with the result automatically.
411 * @param array|null $session
413 protected function loadSession(array &$session = null)
415 if (null === $session) {
416 $session = &$_SESSION;
419 $bags = array_merge($this->bags, array($this->metadataBag));
421 foreach ($bags as $bag) {
422 $key = $bag->getStorageKey();
423 $session[$key] = isset($session[$key]) ? $session[$key] : array();
424 $bag->initialize($session[$key]);
427 $this->started = true;
428 $this->closed = false;