2
0

Zend_Session-AdvancedUsage.xml 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!-- Reviewed: no -->
  3. <sect1 id="zend.session.advanced_usage">
  4. <title>Advanced Usage</title>
  5. <para>
  6. While the basic usage examples are a perfectly acceptable way to utilize Zend Framework sessions, there are some
  7. best practices to consider. This section discusses the finer details of session handling and illustrates more
  8. advanced usage of the Zend_Session component.
  9. </para>
  10. <sect2 id="zend.session.advanced_usage.starting_a_session">
  11. <title>Starting a Session</title>
  12. <para>
  13. If you want all requests to have a session facilitated by Zend_Session, then start the session in the
  14. bootstrap file:
  15. </para>
  16. <example id="zend.session.advanced_usage.starting_a_session.example">
  17. <title>Starting the Global Session</title>
  18. <programlisting language="php"><![CDATA[
  19. Zend_Session::start();
  20. ]]></programlisting>
  21. </example>
  22. <para>
  23. By starting the session in the bootstrap file, you avoid the possibility that your session might be started
  24. after headers have been sent to the browser, which results in an exception, and possibly a broken page for
  25. website viewers. Various advanced features require <classname>Zend_Session::start()</classname> first. (More on
  26. advanced features later.)
  27. </para>
  28. <para>
  29. There are four ways to start a session, when using Zend_Session. Two are wrong.
  30. </para>
  31. <orderedlist>
  32. <listitem>
  33. <para>
  34. Wrong: Do not enable PHP's
  35. <ulink url="http://www.php.net/manual/en/ref.session.php#ini.session.auto-start"><code> session.auto_start</code>
  36. setting</ulink>. If you do not have the ability to disable this setting in
  37. php.ini, you are using mod_php (or equivalent), and the setting is already enabled in
  38. <code>php.ini</code>, then add the following to your <code>.htaccess</code> file (usually in your
  39. HTML document root directory):
  40. <programlisting language="httpd.conf"><![CDATA[
  41. php_value session.auto_start 0
  42. ]]></programlisting>
  43. </para>
  44. </listitem>
  45. <listitem>
  46. <para>
  47. Wrong: Do not use PHP's
  48. <ulink url="http://www.php.net/session_start"><code>session_start()</code></ulink> function
  49. directly. If you use <code>session_start()</code> directly, and then start using
  50. <classname>Zend_Session_Namespace</classname>, an exception will be thrown by
  51. <classname>Zend_Session::start()</classname> ("session has already been started"). If you call
  52. <code>session_start()</code> after using <classname>Zend_Session_Namespace</classname> or calling
  53. <classname>Zend_Session::start()</classname>, an error of level <code>E_NOTICE</code> will be generated, and
  54. the call will be ignored.
  55. </para>
  56. </listitem>
  57. <listitem>
  58. <para>
  59. Correct: Use <classname>Zend_Session::start()</classname>. If you want all requests to have and use
  60. sessions, then place this function call early and unconditionally in your bootstrap code.
  61. Sessions have some overhead. If some requests need sessions, but other requests will not need to use
  62. sessions, then:
  63. </para>
  64. <itemizedlist mark="opencircle">
  65. <listitem>
  66. <para>
  67. Unconditionally set the <code>strict</code> option to <constant>TRUE</constant> using
  68. <classname>Zend_Session::setOptions()</classname> in your bootstrap.
  69. </para>
  70. </listitem>
  71. <listitem>
  72. <para>
  73. Call <classname>Zend_Session::start()</classname> only for requests that need to use sessions and
  74. before any <classname>Zend_Session_Namespace</classname> objects are instantiated.
  75. </para>
  76. </listitem>
  77. <listitem>
  78. <para>
  79. Use "<code>new Zend_Session_Namespace()</code>" normally, where needed, but make sure
  80. <classname>Zend_Session::start()</classname> has been called previously.
  81. </para>
  82. </listitem>
  83. </itemizedlist>
  84. <para>
  85. The <code>strict</code> option prevents <code>new Zend_Session_Namespace()</code> from automatically
  86. starting the session using <classname>Zend_Session::start()</classname>. Thus, this option helps application
  87. developers enforce a design decision to avoid using sessions for certain requests, since it causes
  88. an exception to be thrown when <classname>Zend_Session_Namespace</classname> is instantiated before
  89. <classname>Zend_Session::start()</classname> is called. Developers should carefully consider the impact of
  90. using <classname>Zend_Session::setOptions()</classname>, since these options have global effect, owing to
  91. their correspondence to the underlying options for ext/session.
  92. </para>
  93. </listitem>
  94. <listitem>
  95. <para>
  96. Correct: Just instantiate <classname>Zend_Session_Namespace</classname> whenever needed, and the underlying
  97. PHP session will be automatically started. This offers extremely simple usage that works well in
  98. most situations. However, you then become responsible for ensuring that the first
  99. <code>new Zend_Session_Namespace()</code> happens <emphasis>before</emphasis> any
  100. output (e.g., <ulink url="http://www.php.net/headers_sent">HTTP headers</ulink>) has been sent by
  101. PHP to the client, if you are using the default, cookie-based sessions (strongly recommended). See
  102. <xref linkend="zend.session.global_session_management.headers_sent" /> for more information.
  103. </para>
  104. </listitem>
  105. </orderedlist>
  106. </sect2>
  107. <sect2 id="zend.session.advanced_usage.locking">
  108. <title>Locking Session Namespaces</title>
  109. <para>
  110. Session namespaces can be locked, to prevent further alterations to the data in that namespace. Use
  111. <code>lock()</code> to make a specific namespace read-only, <code>unLock()</code> to make a read-only
  112. namespace read-write, and <code>isLocked()</code> to test if a namespace has been previously locked. Locks
  113. are transient and do not persist from one request to the next. Locking the namespace has no effect on setter
  114. methods of objects stored in the namespace, but does prevent the use of the namespace's setter method to
  115. remove or replace objects stored directly in the namespace. Similarly, locking
  116. <classname>Zend_Session_Namespace</classname> instances does not prevent the use of symbol table aliases to the same
  117. data (see <ulink url="http://www.php.net/references">PHP references</ulink>).
  118. </para>
  119. <example id="zend.session.advanced_usage.locking.example.basic">
  120. <title>Locking Session Namespaces</title>
  121. <programlisting language="php"><![CDATA[
  122. $userProfileNamespace = new Zend_Session_Namespace('userProfileNamespace');
  123. // marking session as read only locked
  124. $userProfileNamespace->lock();
  125. // unlocking read-only lock
  126. if ($userProfileNamespace->isLocked()) {
  127. $userProfileNamespace->unLock();
  128. }
  129. ]]></programlisting>
  130. </example>
  131. </sect2>
  132. <sect2 id="zend.session.advanced_usage.expiration">
  133. <title>Namespace Expiration</title>
  134. <para>
  135. Limits can be placed on the longevity of both namespaces and individual keys in namespaces. Common use cases
  136. include passing temporary information between requests, and reducing exposure to certain security risks by
  137. removing access to potentially sensitive information some time after authentication occurred. Expiration can
  138. be based on either elapsed seconds or the number of "hops", where a hop occurs for each successive request.
  139. </para>
  140. <example id="zend.session.advanced_usage.expiration.example">
  141. <title>Expiration Examples</title>
  142. <programlisting language="php"><![CDATA[
  143. $s = new Zend_Session_Namespace('expireAll');
  144. $s->a = 'apple';
  145. $s->p = 'pear';
  146. $s->o = 'orange';
  147. $s->setExpirationSeconds(5, 'a'); // expire only the key "a" in 5 seconds
  148. // expire entire namespace in 5 "hops"
  149. $s->setExpirationHops(5);
  150. $s->setExpirationSeconds(60);
  151. // The "expireAll" namespace will be marked "expired" on
  152. // the first request received after 60 seconds have elapsed,
  153. // or in 5 hops, whichever happens first.
  154. ]]></programlisting>
  155. </example>
  156. <para>
  157. When working with data expiring from the session in the current request, care should be used when retrieving
  158. them. Although the data are returned by reference, modifying the data will not make expiring data persist
  159. past the current request. In order to "reset" the expiration time, fetch the data into temporary variables,
  160. use the namespace to unset them, and then set the appropriate keys again.
  161. </para>
  162. </sect2>
  163. <sect2 id="zend.session.advanced_usage.controllers">
  164. <title>Session Encapsulation and Controllers</title>
  165. <para>
  166. Namespaces can also be used to separate session access by controllers to protect variables from
  167. contamination. For example, an authentication controller might keep its session state data separate from all
  168. other controllers for meeting security requirements.
  169. </para>
  170. <example id="zend.session.advanced_usage.controllers.example">
  171. <title>Namespaced Sessions for Controllers with Automatic Expiration</title>
  172. <para>
  173. The following code, as part of a controller that displays a test question, initiates a boolean variable
  174. to represent whether or not a submitted answer to the test question should be accepted. In this case,
  175. the application user is given 300 seconds to answer the displayed question.
  176. </para>
  177. <programlisting language="php"><![CDATA[
  178. // ...
  179. // in the question view controller
  180. $testSpace = new Zend_Session_Namespace('testSpace');
  181. // expire only this variable
  182. $testSpace->setExpirationSeconds(300, 'accept_answer');
  183. $testSpace->accept_answer = true;
  184. //...
  185. ]]></programlisting>
  186. <para>
  187. Below, the controller that processes the answers to test questions determines whether or not to accept
  188. an answer based on whether the user submitted the answer within the allotted time:
  189. </para>
  190. <programlisting language="php"><![CDATA[
  191. // ...
  192. // in the answer processing controller
  193. $testSpace = new Zend_Session_Namespace('testSpace');
  194. if ($testSpace->accept_answer === true) {
  195. // within time
  196. }
  197. else {
  198. // not within time
  199. }
  200. // ...
  201. ]]></programlisting>
  202. </example>
  203. </sect2>
  204. <sect2 id="zend.session.advanced_usage.single_instance">
  205. <title>Preventing Multiple Instances per Namespace</title>
  206. <para>
  207. Although <link linkend="zend.session.advanced_usage.locking">session locking</link> provides a good degree
  208. of protection against unintended use of namespaced session data, <classname>Zend_Session_Namespace</classname> also
  209. features the ability to prevent the creation of multiple instances corresponding to a single namespace.
  210. </para>
  211. <para>
  212. To enable this behavior, pass <constant>TRUE</constant> to the second constructor argument when creating the last
  213. allowed instance of <classname>Zend_Session_Namespace</classname>. Any subsequent attempt to instantiate the same
  214. namespace would result in a thrown exception.
  215. </para>
  216. <example id="zend.session.advanced_usage.single_instance.example">
  217. <title>Limiting Session Namespace Access to a Single Instance</title>
  218. <programlisting language="php"><![CDATA[
  219. // create an instance of a namespace
  220. $authSpaceAccessor1 = new Zend_Session_Namespace('Zend_Auth');
  221. // create another instance of the same namespace, but disallow any
  222. // new instances
  223. $authSpaceAccessor2 = new Zend_Session_Namespace('Zend_Auth', true);
  224. // making a reference is still possible
  225. $authSpaceAccessor3 = $authSpaceAccessor2;
  226. $authSpaceAccessor1->foo = 'bar';
  227. assert($authSpaceAccessor2->foo, 'bar');
  228. try {
  229. $aNamespaceObject = new Zend_Session_Namespace('Zend_Auth');
  230. } catch (Zend_Session_Exception $e) {
  231. echo 'Cannot instantiate this namespace since ' .
  232. '$authSpaceAccessor2 was created\n';
  233. }
  234. ]]></programlisting>
  235. </example>
  236. <para>
  237. The second parameter in the constructor above tells <classname>Zend_Session_Namespace</classname> that any future
  238. instances with the "<classname>Zend_Auth</classname>" namespace are not allowed. Attempting to create such an instance
  239. causes an exception to be thrown by the constructor. The developer therefore becomes responsible for storing
  240. a reference to an instance object (<code>$authSpaceAccessor1</code>, <code>$authSpaceAccessor2</code>, or
  241. <code>$authSpaceAccessor3</code> in the example above) somewhere, if access to the session namespace is
  242. needed at a later time during the same request. For example, a developer may store the reference in a static
  243. variable, add the reference to a
  244. <ulink url="http://www.martinfowler.com/eaaCatalog/registry.html">registry</ulink> (see
  245. <xref linkend="zend.registry" />), or otherwise make it available to other methods that may need access to
  246. the session namespace.
  247. </para>
  248. </sect2>
  249. <sect2 id="zend.session.advanced_usage.arrays">
  250. <title>Working with Arrays</title>
  251. <para>
  252. Due to the implementation history of PHP magic methods, modifying an array inside a namespace may not work
  253. under PHP versions before 5.2.1. If you will only be working with PHP 5.2.1 or later, then you may <link
  254. linkend="zend.session.advanced_usage.objects">skip to the next section</link>.
  255. </para>
  256. <example id="zend.session.advanced_usage.arrays.example.modifying">
  257. <title>Modifying Array Data with a Session Namespace</title>
  258. <para>
  259. The following illustrates how the problem may be reproduced:
  260. </para>
  261. <programlisting language="php"><![CDATA[
  262. $sessionNamespace = new Zend_Session_Namespace();
  263. $sessionNamespace->array = array();
  264. // may not work as expected before PHP 5.2.1
  265. $sessionNamespace->array['testKey'] = 1;
  266. echo $sessionNamespace->array['testKey'];
  267. ]]></programlisting>
  268. </example>
  269. <example id="zend.session.advanced_usage.arrays.example.building_prior">
  270. <title>Building Arrays Prior to Session Storage</title>
  271. <para>
  272. If possible, avoid the problem altogether by storing arrays into a session namespace only after all
  273. desired array values have been set.
  274. </para>
  275. <programlisting language="php"><![CDATA[
  276. $sessionNamespace = new Zend_Session_Namespace('Foo');
  277. $sessionNamespace->array = array('a', 'b', 'c');
  278. ]]></programlisting>
  279. </example>
  280. <para>
  281. If you are using an affected version of PHP and need to modify the array after assigning it to a session
  282. namespace key, you may use either or both of the following workarounds.
  283. </para>
  284. <example id="zend.session.advanced_usage.arrays.example.workaround.reassign">
  285. <title>Workaround: Reassign a Modified Array</title>
  286. <para>
  287. In the code that follows, a copy of the stored array is created, modified, and reassigned to the
  288. location from which the copy was created, overwriting the original array.
  289. </para>
  290. <programlisting language="php"><![CDATA[
  291. $sessionNamespace = new Zend_Session_Namespace();
  292. // assign the initial array
  293. $sessionNamespace->array = array('tree' => 'apple');
  294. // make a copy of the array
  295. $tmp = $sessionNamespace->array;
  296. // modfiy the array copy
  297. $tmp['fruit'] = 'peach';
  298. // assign a copy of the array back to the session namespace
  299. $sessionNamespace->array = $tmp;
  300. echo $sessionNamespace->array['fruit']; // prints "peach"
  301. ]]></programlisting>
  302. </example>
  303. <example id="zend.session.advanced_usage.arrays.example.workaround.reference">
  304. <title>Workaround: store array containing reference</title>
  305. <para>
  306. Alternatively, store an array containing a reference to the desired array, and then access it
  307. indirectly.
  308. </para>
  309. <programlisting language="php"><![CDATA[
  310. $myNamespace = new Zend_Session_Namespace('myNamespace');
  311. $a = array(1, 2, 3);
  312. $myNamespace->someArray = array( &$a );
  313. $a['foo'] = 'bar';
  314. echo $myNamespace->someArray['foo']; // prints "bar"
  315. ]]></programlisting>
  316. </example>
  317. </sect2>
  318. <sect2 id="zend.session.advanced_usage.objects">
  319. <title>Using Sessions with Objects</title>
  320. <para>
  321. If you plan to persist objects in the PHP session, know that they will be
  322. <ulink url="http://www.php.net/manual/en/language.oop.serialization.php">serialized</ulink> for storage.
  323. Thus, any object persisted with the PHP session must be unserialized upon retrieval from storage. The
  324. implication is that the developer must ensure that the classes for the persisted objects must have been
  325. defined before the object is unserialized from session storage. If an unserialized object's class is not
  326. defined, then it becomes an instance of <code>stdClass</code>.
  327. </para>
  328. </sect2>
  329. <sect2 id="zend.session.advanced_usage.testing">
  330. <title>Using Sessions with Unit Tests</title>
  331. <para>
  332. Zend Framework relies on PHPUnit to facilitate testing of itself. Many developers extend the existing
  333. suite of unit tests to cover the code in their applications. The exception
  334. "<emphasis>Zend_Session is currently marked as read-only</emphasis>" is thrown while
  335. performing unit tests, if any write-related methods are used after ending the session. However, unit tests
  336. using Zend_Session require extra attention, because closing (<classname>Zend_Session::writeClose()</classname>), or
  337. destroying a session (<classname>Zend_Session::destroy()</classname>) prevents any further setting or unsetting of
  338. keys in any instance of <classname>Zend_Session_Namespace</classname>. This behavior is a direct result of the
  339. underlying ext/session mechanism and PHP's <code>session_destroy()</code> and
  340. <code>session_write_close()</code>, which have no "undo" mechanism to facilitate setup/teardown with unit
  341. tests.
  342. </para>
  343. <para>
  344. To work around this, see the unit test <code>testSetExpirationSeconds()</code> in
  345. <code>SessionTest.php</code> and <code>SessionTestHelper.php</code>, both located in
  346. <code>tests/Zend/Session</code>, which make use of PHP's <code>exec()</code> to launch a separate process.
  347. The new process more accurately simulates a second, successive request from a browser. The separate process
  348. begins with a "clean" session, just like any PHP script execution for a web request. Also, any changes to
  349. <code>$_SESSION</code> made in the calling process become available to the child process, provided the
  350. parent closed the session before using <code>exec()</code>.
  351. </para>
  352. <example id="zend.session.advanced_usage.testing.example">
  353. <title>PHPUnit Testing Code Dependent on Zend_Session</title>
  354. <programlisting language="php"><![CDATA[
  355. // testing setExpirationSeconds()
  356. $script = 'SessionTestHelper.php';
  357. $s = new Zend_Session_Namespace('space');
  358. $s->a = 'apple';
  359. $s->o = 'orange';
  360. $s->setExpirationSeconds(5);
  361. Zend_Session::regenerateId();
  362. $id = Zend_Session::getId();
  363. session_write_close(); // release session so process below can use it
  364. sleep(4); // not long enough for things to expire
  365. exec($script . "expireAll $id expireAll", $result);
  366. $result = $this->sortResult($result);
  367. $expect = ';a === apple;o === orange;p === pear';
  368. $this->assertTrue($result === $expect,
  369. "iteration over default Zend_Session namespace failed; " .
  370. "expecting result === '$expect', but got '$result'");
  371. sleep(2); // long enough for things to expire (total of 6 seconds
  372. // waiting, but expires in 5)
  373. exec($script . "expireAll $id expireAll", $result);
  374. $result = array_pop($result);
  375. $this->assertTrue($result === '',
  376. "iteration over default Zend_Session namespace failed; " .
  377. "expecting result === '', but got '$result')");
  378. session_start(); // resume artificially suspended session
  379. // We could split this into a separate test, but actually, if anything
  380. // leftover from above contaminates the tests below, that is also a
  381. // bug that we want to know about.
  382. $s = new Zend_Session_Namespace('expireGuava');
  383. $s->setExpirationSeconds(5, 'g'); // now try to expire only 1 of the
  384. // keys in the namespace
  385. $s->g = 'guava';
  386. $s->p = 'peach';
  387. $s->p = 'plum';
  388. session_write_close(); // release session so process below can use it
  389. sleep(6); // not long enough for things to expire
  390. exec($script . "expireAll $id expireGuava", $result);
  391. $result = $this->sortResult($result);
  392. session_start(); // resume artificially suspended session
  393. $this->assertTrue($result === ';p === plum',
  394. "iteration over named Zend_Session namespace failed (result=$result)");
  395. ]]></programlisting>
  396. </example>
  397. </sect2>
  398. </sect1>