Advanced Usage - Zend_Session

Advanced Usage

While the basic usage examples are a perfectly acceptable way to utilize Zend Framework sessions, there are some best practices to consider. This section discusses the finer details of session handling and illustrates more advanced usage of the Zend_Session component.

Starting a Session

If you want all requests to have a session facilitated by Zend_Session, then start the session in the bootstrap file:

Example #1 Starting the Global Session

  1. Zend_Session::start();

By starting the session in the bootstrap file, you avoid the possibility that your session might be started after headers have been sent to the browser, which results in an exception, and possibly a broken page for website viewers. Various advanced features require Zend_Session::start() first. (More on advanced features later.)

There are four ways to start a session, when using Zend_Session. Two are wrong.

  1. Wrong: Do not enable PHP's » session.auto_start setting. If you do not have the ability to disable this setting in php.ini, you are using mod_php (or equivalent), and the setting is already enabled in php.ini, then add the following to your .htaccess file (usually in your HTML document root directory):

    1. php_value session.auto_start 0
  2. Wrong: Do not use PHP's » session_start() function directly. If you use session_start() directly, and then start using Zend_Session_Namespace, an exception will be thrown by Zend_Session::start() ("session has already been started"). If you call session_start() after using Zend_Session_Namespace or calling Zend_Session::start(), an error of level E_NOTICE will be generated, and the call will be ignored.

  3. Correct: Use Zend_Session::start(). If you want all requests to have and use sessions, then place this function call early and unconditionally in your bootstrap code. Sessions have some overhead. If some requests need sessions, but other requests will not need to use sessions, then:

    • Unconditionally set the strict option to TRUE using Zend_Session::setOptions() in your bootstrap.

    • Call Zend_Session::start() only for requests that need to use sessions and before any Zend_Session_Namespace objects are instantiated.

    • Use "new Zend_Session_Namespace()" normally, where needed, but make sure Zend_Session::start() has been called previously.

    The strict option prevents new Zend_Session_Namespace() from automatically starting the session using Zend_Session::start(). Thus, this option helps application developers enforce a design decision to avoid using sessions for certain requests, since it causes an exception to be thrown when Zend_Session_Namespace is instantiated before Zend_Session::start() is called. Developers should carefully consider the impact of using Zend_Session::setOptions(), since these options have global effect, owing to their correspondence to the underlying options for ext/session.

  4. Correct: Just instantiate Zend_Session_Namespace whenever needed, and the underlying PHP session will be automatically started. This offers extremely simple usage that works well in most situations. However, you then become responsible for ensuring that the first new Zend_Session_Namespace() happens before any output (e.g., » HTTP headers) has been sent by PHP to the client, if you are using the default, cookie-based sessions (strongly recommended). See this section for more information.

Locking Session Namespaces

Session namespaces can be locked, to prevent further alterations to the data in that namespace. Use lock() to make a specific namespace read-only, unLock() to make a read-only namespace read-write, and isLocked() to test if a namespace has been previously locked. Locks are transient and do not persist from one request to the next. Locking the namespace has no effect on setter methods of objects stored in the namespace, but does prevent the use of the namespace's setter method to remove or replace objects stored directly in the namespace. Similarly, locking Zend_Session_Namespace instances does not prevent the use of symbol table aliases to the same data (see » PHP references).

Example #2 Locking Session Namespaces

  1. $userProfileNamespace = new Zend_Session_Namespace('userProfileNamespace');
  3. // marking session as read only locked
  4. $userProfileNamespace->lock();
  6. // unlocking read-only lock
  7. if ($userProfileNamespace->isLocked()) {
  8.     $userProfileNamespace->unLock();
  9. }

Namespace Expiration

Limits can be placed on the longevity of both namespaces and individual keys in namespaces. Common use cases include passing temporary information between requests, and reducing exposure to certain security risks by removing access to potentially sensitive information some time after authentication occurred. Expiration can be based on either elapsed seconds or the number of "hops", where a hop occurs for each successive request.

Example #3 Expiration Examples

  1. $s = new Zend_Session_Namespace('expireAll');
  2. $s->a = 'apple';
  3. $s->p = 'pear';
  4. $s->o = 'orange';
  6. $s->setExpirationSeconds(5, 'a'); // expire only the key "a" in 5 seconds
  8. // expire entire namespace in 5 "hops"
  9. $s->setExpirationHops(5);
  11. $s->setExpirationSeconds(60);
  12. // The "expireAll" namespace will be marked "expired" on
  13. // the first request received after 60 seconds have elapsed,
  14. // or in 5 hops, whichever happens first.

When working with data expiring from the session in the current request, care should be used when retrieving them. Although the data are returned by reference, modifying the data will not make expiring data persist past the current request. In order to "reset" the expiration time, fetch the data into temporary variables, use the namespace to unset them, and then set the appropriate keys again.

Session Encapsulation and Controllers

Namespaces can also be used to separate session access by controllers to protect variables from contamination. For example, an authentication controller might keep its session state data separate from all other controllers for meeting security requirements.

Example #4 Namespaced Sessions for Controllers with Automatic Expiration

The following code, as part of a controller that displays a test question, initiates a boolean variable to represent whether or not a submitted answer to the test question should be accepted. In this case, the application user is given 300 seconds to answer the displayed question.

  1. // ...
  2. // in the question view controller
  3. $testSpace = new Zend_Session_Namespace('testSpace');
  4. // expire only this variable
  5. $testSpace->setExpirationSeconds(300, 'accept_answer');
  6. $testSpace->accept_answer = true;
  7. //...

Below, the controller that processes the answers to test questions determines whether or not to accept an answer based on whether the user submitted the answer within the allotted time:

  1. // ...
  2. // in the answer processing controller
  3. $testSpace = new Zend_Session_Namespace('testSpace');
  4. if ($testSpace->accept_answer === true) {
  5.     // within time
  6. }
  7. else {
  8.     // not within time
  9. }
  10. // ...

Preventing Multiple Instances per Namespace

Although session locking provides a good degree of protection against unintended use of namespaced session data, Zend_Session_Namespace also features the ability to prevent the creation of multiple instances corresponding to a single namespace.

To enable this behavior, pass TRUE to the second constructor argument when creating the last allowed instance of Zend_Session_Namespace. Any subsequent attempt to instantiate the same namespace would result in a thrown exception.

Example #5 Limiting Session Namespace Access to a Single Instance

  1. // create an instance of a namespace
  2. $authSpaceAccessor1 = new Zend_Session_Namespace('Zend_Auth');
  4. // create another instance of the same namespace, but disallow any
  5. // new instances
  6. $authSpaceAccessor2 = new Zend_Session_Namespace('Zend_Auth', true);
  8. // making a reference is still possible
  9. $authSpaceAccessor3 = $authSpaceAccessor2;
  11. $authSpaceAccessor1->foo = 'bar';
  13. assert($authSpaceAccessor2->foo, 'bar');
  15. try {
  16.     $aNamespaceObject = new Zend_Session_Namespace('Zend_Auth');
  17. } catch (Zend_Session_Exception $e) {
  18.     echo 'Cannot instantiate this namespace since ' .
  19.          '$authSpaceAccessor2 was created\n';
  20. }

The second parameter in the constructor above tells Zend_Session_Namespace that any future instances with the "Zend_Auth" namespace are not allowed. Attempting to create such an instance causes an exception to be thrown by the constructor. The developer therefore becomes responsible for storing a reference to an instance object ($authSpaceAccessor1, $authSpaceAccessor2, or $authSpaceAccessor3 in the example above) somewhere, if access to the session namespace is needed at a later time during the same request. For example, a developer may store the reference in a static variable, add the reference to a » registry (see Zend_Registry), or otherwise make it available to other methods that may need access to the session namespace.

Working with Arrays

Due to the implementation history of PHP magic methods, modifying an array inside a namespace may not work under PHP versions before 5.2.1. If you will only be working with PHP 5.2.1 or later, then you may skip to the next section.

Example #6 Modifying Array Data with a Session Namespace

The following illustrates how the problem may be reproduced:

  1. $sessionNamespace = new Zend_Session_Namespace();
  2. $sessionNamespace->array = array();
  4. // may not work as expected before PHP 5.2.1
  5. $sessionNamespace->array['testKey'] = 1;
  6. echo $sessionNamespace->array['testKey'];

Example #7 Building Arrays Prior to Session Storage

If possible, avoid the problem altogether by storing arrays into a session namespace only after all desired array values have been set.

  1. $sessionNamespace = new Zend_Session_Namespace('Foo');
  2. $sessionNamespace->array = array('a', 'b', 'c');

If you are using an affected version of PHP and need to modify the array after assigning it to a session namespace key, you may use either or both of the following workarounds.

Example #8 Workaround: Reassign a Modified Array

In the code that follows, a copy of the stored array is created, modified, and reassigned to the location from which the copy was created, overwriting the original array.

  1. $sessionNamespace = new Zend_Session_Namespace();
  3. // assign the initial array
  4. $sessionNamespace->array = array('tree' => 'apple');
  6. // make a copy of the array
  7. $tmp = $sessionNamespace->array;
  9. // modfiy the array copy
  10. $tmp['fruit'] = 'peach';
  12. // assign a copy of the array back to the session namespace
  13. $sessionNamespace->array = $tmp;
  15. echo $sessionNamespace->array['fruit']; // prints "peach"

Example #9 Workaround: store array containing reference

Alternatively, store an array containing a reference to the desired array, and then access it indirectly.

  1. $myNamespace = new Zend_Session_Namespace('myNamespace');
  2. $a = array(1, 2, 3);
  3. $myNamespace->someArray = array( &$a );
  4. $a['foo'] = 'bar';
  5. echo $myNamespace->someArray['foo']; // prints "bar"

Using Sessions with Objects

If you plan to persist objects in the PHP session, know that they will be » serialized for storage. Thus, any object persisted with the PHP session must be unserialized upon retrieval from storage. The implication is that the developer must ensure that the classes for the persisted objects must have been defined before the object is unserialized from session storage. If an unserialized object's class is not defined, then it becomes an instance of stdClass.

Using Sessions with Unit Tests

Zend Framework relies on PHPUnit to facilitate testing of itself. Many developers extend the existing suite of unit tests to cover the code in their applications. The exception "Zend_Session is currently marked as read-only" is thrown while performing unit tests, if any write-related methods are used after ending the session. However, unit tests using Zend_Session require extra attention, because closing ( Zend_Session::writeClose()), or destroying a session ( Zend_Session::destroy()) prevents any further setting or unsetting of keys in any instance of Zend_Session_Namespace. This behavior is a direct result of the underlying ext/session mechanism and PHP's session_destroy() and session_write_close(), which have no "undo" mechanism to facilitate setup/teardown with unit tests.

To work around this, see the unit test testSetExpirationSeconds() in SessionTest.php and SessionTestHelper.php, both located in tests/Zend/Session, which make use of PHP's exec() to launch a separate process. The new process more accurately simulates a second, successive request from a browser. The separate process begins with a "clean" session, just like any PHP script execution for a web request. Also, any changes to $_SESSION made in the calling process become available to the child process, provided the parent closed the session before using exec().

Example #10 PHPUnit Testing Code Dependent on Zend_Session

  1. // testing setExpirationSeconds()
  2. $script = 'SessionTestHelper.php';
  3. $s = new Zend_Session_Namespace('space');
  4. $s->a = 'apple';
  5. $s->o = 'orange';
  6. $s->setExpirationSeconds(5);
  8. Zend_Session::regenerateId();
  9. $id = Zend_Session::getId();
  10. session_write_close(); // release session so process below can use it
  11. sleep(4); // not long enough for things to expire
  12. exec($script . "expireAll $id expireAll", $result);
  13. $result = $this->sortResult($result);
  14. $expect = ';a === apple;o === orange;p === pear';
  15. $this->assertTrue($result === $expect,
  16.     "iteration over default Zend_Session namespace failed; " .
  17.     "expecting result === '$expect', but got '$result'");
  19. sleep(2); // long enough for things to expire (total of 6 seconds
  20.           // waiting, but expires in 5)
  21. exec($script . "expireAll $id expireAll", $result);
  22. $result = array_pop($result);
  23. $this->assertTrue($result === '',
  24.     "iteration over default Zend_Session namespace failed; " .
  25.     "expecting result === '', but got '$result')");
  26. session_start(); // resume artificially suspended session
  28. // We could split this into a separate test, but actually, if anything
  29. // leftover from above contaminates the tests below, that is also a
  30. // bug that we want to know about.
  31. $s = new Zend_Session_Namespace('expireGuava');
  32. $s->setExpirationSeconds(5, 'g'); // now try to expire only 1 of the
  33.                                   // keys in the namespace
  34. $s->g = 'guava';
  35. $s->p = 'peach';
  36. $s->p = 'plum';
  38. session_write_close(); // release session so process below can use it
  39. sleep(6); // not long enough for things to expire
  40. exec($script . "expireAll $id expireGuava", $result);
  41. $result = $this->sortResult($result);
  42. session_start(); // resume artificially suspended session
  43. $this->assertTrue($result === ';p === plum',
  44.     "iteration over named Zend_Session namespace failed (result=$result)");


© 2006-2022 by Zend by Perforce. Made with by awesome contributors.

This website is built using zend-expressive and it runs on PHP 7.