This will record the variable name and track its value.The variable will be tracked until the session ends, or until you manually deregister it.. Using Session Variables To bring a sessi
Trang 1$_SESSION['myvar'] = 5;
or
$HTTP_SESSION_VARS['myvar'] = 5;
If you are using an older version of PHP, or if you have register_globalsturned on,
in order for a variable to be tracked from one script to another, you can to register it with a call to session_register() For example, to register the variable $myvar, you could use the following code
$myvar = 5;
session_register('myvar');
Note that you need to pass a string containing the name of the variable to
session_register().This string should not include the $symbol
This will record the variable name and track its value.The variable will be tracked until the session ends, or until you manually deregister it
You can register more than one variable at once by providing a comma-separated list
of variable names; for example
session_register('myvar1', 'myvar2');
If you are using the $_SESSIONor $HTTP_SESSION_VARSarrays, do not try and use the
session_register()function
Using Session Variables
To bring a session variable into scope so that it can be used, you must first start a session
You can then access the variable via the arrays $_SESSIONor $HTTP_SESSION_VARSas, for example,$HTTP_SESSION_VARS['myvar'] If you have register_globalsturned on you can access it via its short form name, for example $myvar
If you have register_globalson, bear in mind that a session variable cannot be overridden by GETor POSTdata, which is a good security feature, but something to bear
in mind when coding
On the other hand, you need to be careful when checking if session variables have been set (via, say,isset()or empty()) Remember that variables can be set by the user via GETor POST.You can check a variable to see if it is a registered session variable by calling the session_is_registered()function.You call this function like this:
$result = session_is_registered('myvar');
This will check whether $myvaris a registered session variable and return trueor
false
If using $_SESSIONor $HTTP_POST_VARSyou should NOT use the session_is_reg-istered()function.You can just check whether the array elements are set directly using, for example:
if (isset($HTTP_SESSION_VARS['myvar']))
Trang 2418 Chapter 20 Using Session Control in PHP
Deregistering Variables and Destroying the Session
When you are finished with a session variable, you can deregister it
If you are using the $_SESSION or $HTTP_SESSION_VARS arrays, you can do this directly, for example:
unset($HTTP_SESSION_VARS['myvar']);
If you have register_globals on, you need to clear session variables using the
session_unregister()function, as follows:
session_unregister("myvar");
Again, this function requires the name of the variable you want to deregister as a string, without the $symbol.This function can only deregister a single session variable at a time (unlike session_register()).You can, however, use session_unset()to deregister all the current session variables
Do not try to use the session_unregister()function if you are using
$_SESSION or $HTTP_SESSION_VARSdirectly
When you are finished with a session, you should first deregister all the variables and then call
session_destroy();
to clean up the session ID
Simple Session Example
Some of this might seem a little abstract, so let’s look at an example.We’ll implement a set of three pages
On the first page, we’ll start a session and register the variable
$HTTP_SESSION_VARS['sess_var'].The code to do this is shown in Listing 20.1
Listing 20.1 page1.php—Starting a Session and Registering a Variable
<?php session_start();
$HTTP_SESSION_VARS['sess_var'] = "Hello world!";
echo 'The content of $HTTP_SESSION_VARS[\'sess_var\'] is ' $HTTP_SESSION_VARS['sess_var'].'<br />';
?>
<a href="page2.php">Next page</a>
We have registered the variable and set its value.The output of this script is shown in Figure 20.1
Trang 3Figure 20.1 Initial value of the session variable shown by page1.php.
The final value of the variable on the page is the one that will be available on subsequent pages At the end of the script, the session variable is serialized, or frozen, until it is
reloaded via the next call to session_start()
We therefore begin the next script by calling session_start().This script is shown
in Listing 20.2
Listing 20.2 page2.php—Accessing a Session Variable and Deregistering It
<?php session_start();
echo 'The content of $HTTP_SESSION_VARS[\'sess_var\'] is ' $HTTP_SESSION_VARS['sess_var'].'<br />';
unset($HTTP_SESSION_VARS['sess_var']);
?>
<a href="page3.php">Next page</a>
After calling session_start(), the variable $HTTP_SESSION_VARS['sess_var']is avail-able with its previously stored value, as you can see in Figure 20.2
Figure 20.2 The value of the session variable has been passed along via the session ID to page2.php.
Trang 4420 Chapter 20 Using Session Control in PHP
After we have used the variable, we unset it.The session still exists, but the variable
$HTTP_SESSION_VARS['sess_var']is no longer a registered variable
Finally we pass along to page3.php, the final script in our example.The code for this script is shown in Listing 20.3
Listing 20.3 page3.php—Ending the Session
<?php
session_start();
echo 'The content of $HTTP_SESSION_VARS[\'sess_var\'] is ' $HTTP_SESSION_VARS['sess_var'].'<br />';
session_destroy();
?>
As you can see in Figure 20.3, we no longer have access to the persistent value of
$HTTP_SESSION_VARS['sess_var'] With some PHP versions prior to 4.3 you might encounter a bug when trying to unset elements of $HTTP_SESSION_VARS or $_SESSION If you find that you are unable to unset elements (that is, they stay set) you can revert to using session_unreg-ister()to clear these variables
Using session_unregister()is no longer recommended, but if you want your code
to work reliably on all versions of PHP4 it is your only option
Figure 20.3 The deregistered variable is no longer available.
We finish by calling session_destroy()to dispose of the session ID
Trang 5Configuring Session Control
There is a set of configuration options for sessions that you can set in your php.inifile
Some of the more useful options, and a description of each, are shown in Table 20.1
Table 20.1 Session Configuration Options
session.auto_start 0 (disabled) Automatically starts sessions.
session.cache_expire 180 Sets time-to-live for cached session pages, in
minutes.
session.cookie_domain none Domain to set in session cookie.
session.cookie_lifetime 0 How long the session ID cookie will last on
the user’s machine.The default, 0, will last until the browser is closed.
session.cookie_path / Path to set in session cookie.
session.name PHPSESSID The name of the session that is used as the
cookie name on a user’s system.
session.save_handler files Defines where session data is stored.You can
set this to point to a database, but you have
to write your own functions.
session.save_path /tmp The path where session data is stored More
generally, the argument passed to the save handled and defined by
session.save_handler
session.use_cookies 1 (enabled) Configures sessions to use cookies on the
client side.
Implementing Authentication with Session Control
Finally, we will look at a more substantial example using session control
Possibly the most common use of session control is to keep track of users after they have been authenticated via a login mechanism In this example, we will combine authentication from a MySQL database with use of sessions to provide this functionality
This functionality will form the basis of the project in Chapter 24, “Building User Authentication and Personalization,” and will be reused in the other projects
We will reuse the authentication database we set up in Chapter 14, “Implementing Authentication with PHP and MySQL,” for using mod_auth_mysql.You can check Listing 14.3 in that chapter for details of the database