A free and open-source book on Zend Framework for beginners


15.1. PHP Sessions

First, let's give some theory on what PHP sessions are. In PHP, sessions work as follows:

49) An HTTP cookie is a small piece of data sent from a website and stored in the user's web browser while the user is browsing. Cookies are used to remember some state between HTTP requests.

From PHP application developer's point of view, the work with sessions is simple. First, initialise the session by calling session_start() PHP function. Then, use $_SESSION super-global array for setting/retrieving session data. For example, to save some data to session, use the following code:

session_start();
$_SESSION['my_var'] = 'Some data';

To later retrieve the data from session, use the following code:

session_start();
if (isset($_SESSION['my_var']))
    $sessionVar = $_SESSION['my_var'];
else 
    $sessionVar = 'Some default value';

To clear the data, use the unset() PHP function, as follows:

unset($_SESSION['my_var']);

Note that sessions do not last forever (they expire sooner or later when the user's cookie expires or when PHP engine cleans up the session storage files). How long the session lasts is defined in php.ini configuration file. It is possible to override the default expiration parameters with the help of ini_set() function, as follows:

// Set session cookie lifetime (in seconds) to be 1 hour.
ini_set('session.cookie_lifetime', 60*60*1);

// Store session data on server for maximum 1 month.
ini_set('session.gc_maxlifetime', 60*60*24*30);

There are several other "advanced" session-related PHP configuration settings in php.ini. We do not cover them here, because they are usually not needed.

So, if PHP sessions is so simple, why do I need additional wrapper provided by Zend Framework 3?

ZF3-provided wrapper around the PHP sessions is useful, because:

  • ZF3 session wrapper is object-oriented, so you can use it consistently in your MVC application.
  • ZF3 provides the concept of session namespaces, so different models can store data without naming conflicts.
  • ZF3 provides security features (session validators), so it is more difficult for a malicious user to hack and substitute your session data.
  • Using $_SESSION super-global array directly is not good, because it makes testing your website more difficult. When you use a wrapper around PHP sessions, it is easier to supply test data.
  • With ZF3 session classes, it is possible to implement custom session data storages (for example, store session data in database instead of files).

Top