Page 226 - Open Soource Technologies 304.indd
P. 226
Web Technologies-I
Notes Registered variables persist between pages, and changes to variables made on one page are
visible from others. For example, an “add this to your shopping cart” link can take the user to
a page that adds an item to a registered array of items in the cart. This registered array can then
be used on another page to display the contents of the cart.
Session Basics
To enable sessions for a page, call session_start( ) before any of the document has been generated:
<?php session_start( )?> <html> ... </html>
This assigns a new session ID if it has to possibly creating a cookie to be sent to the browser,
and loads any persistent variables from the store.
If you have registered objects, the class definitions for those objects must be loaded before the
call to session_start( ).
You can register a variable with the session by passing the name of the variable to session_register
( ). For example, here is a basic hit counter:
<?php session_start( );
session_register(‘hits’);
++$hits;
?>
This page has been viewed
<?= $hits ?> times.
The session_start( ) function loads registered variables into the associative array $HTTP_
SESSION_VARS. The keys are the variables’ names (e.g.,$HTTP_SESSION_VARS[‘hits’]). If
register_globals is enabled in the php.ini file, the variables are also set directly. Because the
array and the variable both reference the same value, setting the value of one also changes the
value of the other.
You can unregister a variable from a session, which removes it from the data store, by calling
session_unregister( ). The session_is_registered( ) function returnstrue if the given variable is
registered. If you are curious, the session_id( ) function returns the current session ID.
To end a session, call session_destroy( ). This removes the data store for the current session, but
it does not remove the cookie from the browser cache. This means that, on subsequent visits
to sessions-enabled pages, the user will have the same session ID she had before the call to
session_destroy( ), but none of the data.
Example shows the first code block from last examples rewritten to use sessions instead of
manually setting cookies.
Setting preferences with sessions
<?php $colors = array(‘black’ => ‘#000000’, ‘white’ => ‘#ffffff’, ‘red’ => ‘#ff0000’, ‘blue’ =>
‘#0000ff’);
session_start( );
session_register(‘bg’);
session_register(‘fg’);
$bg_name = $_POST[‘background’];
$fg_name = $_POST[‘foreground’];
220 LOVELY PROFESSIONAL UNIVERSITY