Integrating with Legacy Sessions

Integrating with Legacy Sessions

Sometimes it may be necessary to integrate Symfony into a legacy application where you do not initially have the level of control you require.

As stated elsewhere, Symfony Sessions are designed to replace the use of PHP’s native session_*() functions and use of the $_SESSION superglobal. Additionally, it is mandatory for Symfony to start the session.

However, when there really are circumstances where this is not possible, you can use a special storage bridge Symfony\Component\HttpFoundation\Session\Storage\PhpBridgeSessionStorage which is designed to allow Symfony to work with a session started outside of the Symfony HttpFoundation component. You are warned that things can interrupt this use-case unless you are careful: for example the legacy application erases $_SESSION.

A typical use of this might look like this:

  1. use Symfony\Component\HttpFoundation\Session\Session;
  2. use Symfony\Component\HttpFoundation\Session\Storage\PhpBridgeSessionStorage;
  3. // legacy application configures session
  4. ini_set('session.save_handler', 'files');
  5. ini_set('session.save_path', '/tmp');
  6. session_start();
  7. // Get Symfony to interface with this existing session
  8. $session = new Session(new PhpBridgeSessionStorage());
  9. // symfony will now interface with the existing PHP session
  10. $session->start();

This will allow you to start using the Symfony Session API and allow migration of your application to Symfony sessions.

Note

Symfony sessions store data like attributes in special ‘Bags’ which use a key in the $_SESSION superglobal. This means that a Symfony session cannot access arbitrary keys in $_SESSION that may be set by the legacy application, although all the $_SESSION contents will be saved when the session is saved.

This work, including the code samples, is licensed under a Creative Commons BY-SA 3.0 license.