Sessions and Session Variables

To keep state you need to utilize session variables. Every time you hit a Web site you start a session, and this session is identified by a unique GUID (Globally Unique Identifier). A session is defined as the period of time during which a unique user interacts with a Web application. As the programmer, you can store variables in this session. This is an extremely useful tool. You don’t have to keep track of each individual user and his state; you just have to reference the session. I’ll discuss how to reference sessions later on.

When working with sessions there are some important things to remember. If you have a server farm running, a user’s session does not follow him as he moves from server to server. In other words, a session is only valid on a single server. The session is process dependent. This means that if your Web server needs to be restarted and there are current sessions active, then the sessions will be lost. One unique feature of sessions in PHP is that they are not cookie dependent. So if a client does not accept HTTP cookies, the client can still take advantage of sessions.

There are currently two methods supported for passing sessions in PHP4:

  • Cookies

  • URL Parameter

Cookies are of course the preferred method, but since they are not always available you can pass the session id along the query string as a URL parameter. Here is an example of how you might pass the session id along the query string in PHP.

<?php
if(!session_is_registered(‘nCount’))
{
    session_register(‘nCount’);
    $nCount = 1;
}
else
{
    $nCount++;
}
?>

<p>Hello, you have seen this page <?php echo $nCount; ?> times.</p>

<p>To continue, <a href=“somepage.php?<?php echo strip_tags(SID)?>”>click here (sompage.php?<?php 
echo strip_tags(SID)?>)</A></p>

In this example we check to see if the session variable nCount is registered. If it is not registered we register it and initialize it. Otherwise we add 1 to the count and display our message to the user. The output of this page might look something like you see in Figure 1.2.

Figure 1.2. An example output of passing a session id.


NOTE

Non-relative URLs are assumed to point to external sites and don’t append the sid as it would be a security risk.

That long number at the end of the link, ada6906d1e4bf2d0c753f91edc585b80, is the session id. PHP stores these sessions in the sessiondata folder, usually C:PHPsessiondata. If you look in this folder you will see files that start with sess_ and end with a long GUID like the one on the end of the URL. This is how PHP itself keeps track of the session data. When you start debugging you will probably reference this folder quite often because you can open up these files and see if the session variables you set are being stored. If they are not being stored then you will need to check your php.ini file to make sure sessions are enabled.

Now that you have a general knowledge of how sessions in PHP work, take a look at the configuration options available to you and what each one of them means. There are 21 configurable options for sessions in PHP (see Table 1.1) and each one of these behaviors is configurable in the php.ini file.

All of these options, except user_trans_sid, can be set anywhere using the ini_set() function.

Table 1.1. Session Configuration Options
Option Name Default Value
save_path “/tmp”
name “PHPSESSID”
save_handler “files”
auto_start 0
serialize_handler “php”
gc_probability 1
gc_dividend 100
gc_maxlifetime 1440
cookie_path “/”
cookie_domain “”
cookie_secure “”
use_cookies 1
use_only_cookies 0
cookie_lifetime 0
referer_check “”
entropy_file “”
entropy_length 0
cache_limiter “nocache”
cache_expire 180
user_trans_sid 0
url_rewriter.tags “a=href,area=href,frame=src,input=src,form=fakeentry”

Here is an overview of each of these configurable session options.

session.save_handler

session.save_handler defines the name of the handler that is used for the sessions data management.

session.save_path

session.save_path This is where the sessions are stored if session.save_handler is set to files. There is an optional N argument to this option that determines the number of directory levels that your sessions will be stored across. For example, setting the save_path option to 5;./temp,where 5 is the optional argument, will result in a directory structure something like this:

./tmp/5/c/4/e/1/sess_ ada6906d1e4bf2d0c753f91edc585b80.

If the N argument is used you must create the directory structure yourself. Also, if you do use the N argument you must surround the session.save_path in quotes because the semicolon is also used for comments in the php.ini file. For our purposes, I do not recommend using this option.

session.name

session.name specifies the name of the session that is used to reference the sessionid in cookies. This should only take alphanumeric characters.

session.auto_start

session.auto_start specifies if the session module should start automatically. If you do use session.auto_start then you cannot put objects into your sessions because the class definition must be loaded before starting the session.

session.serialize_handler

session.serialize_handler is the name of the handler which is used to serialize or deserialize data in the session. Currently only the internal formats “php” and “WDDX” are valid. WDDX is also available only if PHP is compiled with WDDX support.

session.gc_probability and session.gc_dividend

session.gc_probability specifies the probability when the garbage collection process should start. This is calculated by using gc_probability/gc_dividend.

session.gc_maxlifetime

session.gc_maxlifetime is the number of seconds at which the session data is seen as garbage and cleaned up.

session.cookie_path

session.cookie_path is the path for which the cookie is valid.

session.cookie_domain

session.cookie_domain is the domain for which the cookie is valid.

session.cookie_secure

session.cookie_secure tells the cookies whether they should be sent over secure connections only.

session.use_cookies

session.use_cookies specifies if the session module should store session ids on the client side.

session.use_only_cookies

session.use_only_cookies tells the session module that it should only use cookies to store the session ids. This prevents attacks from session variables being passed along the URL.

session.cookie_lifetime

session.cookie_lifetime specifies the lifetime of the cookie in seconds. The default value 0 means wait until the browser is closed to expire the cookie.

session.referer_check

session.referer_check contains a string for which you want to check each HTTP referer. If PHP does not find this substring, the embedded session id will be marked as invalid.

session.entropy_file

session.entropy_file gives a path to an external file that will be used as an addition in creating the session id. The external file will contribute to the randomness in the session creation.

session.entropy_length

session.entropy_length specifies the number of bytes which will be read from the session.entropy_file variable. When set to its default value of 0, it disables the entropy options.

session.cache_limiter

session.cache_limiter specifies the cache control method to use. Valid options for this are none, nocache, private, private_no_expire, and public.

session.cache_expire

session.cache_expire is the time to live for cached session pages in minutes. This option has no effect if session.cache_limiter is set to nocache.

session.user_trans_sid

session.user_trans_sid specifies whether or not transparent sid support is enabled.

url_rewriter.tags

url_rewriter.tags specifies what HTML tags should be rewritten to include the session id if session.user_trans_sid is set to 1.

Wow, there are a lot of configuration options for sessions. PHP is very unique and customizable. You do not have to specify all of these options in the php.ini file; as a matter of fact, PHP gives you several functions that expose these options to your code. So, if you need to change any of these in particular applications you can call on the functions listed in Table 1.2.

Table 1.2. Session Functions
Function Name Arguments Description
session_cache_expire [int new_cache_expire] returns the current setting for session.cache_expire. If new_cache_expire is specified, the current session.cache_expire is replaced with new_cache_expire.
session_cache_limiter [string cache_limiter] returns the name of the current setting for session.cache_limiter. If cache_limiter is specified, the name of session.cache_limiter is set to cache_limiter.
session_decode string val decodes the session data in the variable val.
session_encode void returns an encoded string with the contents of the current session.
session_destroy void destroys the current session and any data associated with the current session.
session_get_cookie_params void returns an array with the current sessions cookie information. The array contains the following items: lifetime, path, domain, and secure.
session_id [string val] returns the current session id. If val is specified it will replace the current session id. If val is specified you must call this before session_start().
session_is_registered string val returns true if there is a global variable with a name specified in val.
session_module_name [string val] returns the name of the current session module. If val is specified, that module will be used instead.
session_name [string name] returns the name of the current session. If name is specified it sets the name of the current session.
session_regenerate_id void will regenerate the session id and replace the current session id with the newly generated session id.
session_register mixed name [, mixed …] accepts a variable number of arguments; any of these arguments can be a string holding the name of a variable or an array consisting of variable names or other arrays. For each of the names specified, session_register() will register a global variable with that name in the current session.
session_save_path [string path] returns the path of the current directory where sessions are being stored. If path is specified, the current path is replaced with path.
session_set_cookie_params int lifetime [,string path] [,string domain] [, bool secure]sets the cookie parameters, lifetime, path, domain, and secure.
session_set_save_handler string open, string close, string read, string write, string destroy, string gc sets the session storage functions used for storing and retrieving data. You would use this when you wanted to create your own session handling functions.
session_start void creates a session or resumes the current session. This is all based on the current session id.
session_unregister string var unregisters global variables with the name specified in var.
session_unset void this frees all session variables currently registered.
session_write_close void this will end the current session and store the session data. You do not need to explicitly call this function.

I know that you are saying to yourself, “What the hell am I supposed to do with all of this?” To tell you the truth, you won’t use half of these functions for what you will be doing. Just because you won’t use them in the examples does not mean that you won’t use them in some of your games. As for the functions you will use, here is an example PHP script that sets some session variables. Do not worry about the syntax of all the code right now; I’ll cover that in Chapter 4. For now, just look at how I am using the functions listed in Table 1.2.

<?php
// use $_SESSION instead of session_register due to security issues
session_start();
$turn = $_SESSION[‘turn’];
if(!isset($turn))
{
    $turn = 1;
    $_SESSION[‘turn’] = $turn;
}

printf(“Current turn value: ” + $_SESSION[‘turn’]);

unset($turn);
session_destroy();
?>

Now take a look and see what this small example is doing. First you start the session using session_start(). Then you attempt to get a variable named turn back from the session. If the variable $turn is not set then you have not yet actually started the session and you need to initialize the variable. After you initialize the variable, it sets the session variable turn to whatever is in the variable $turn. Then, the current value is printed, the variable is unset, and the session is destroyed.

Do not worry if you aren’t comfortable with all of this yet. You will be using sessions in all the projects in this book, so it will make more sense when you see sessions being used in an actual context.

If you’re feeling a bit overwhelmed this would probably be a good time to take a break. If you’re ready for more, continue with the discussion of how the Web server talks to the client with TCP/IP. After that, you will install and configure an IIS (Internet Information Server) Web server and an Apache Web server.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset