Manual for the DB_eSession PHP Class (ver 1.0.2)

Table of Contents

  1. Introduction.
  2. Features.
  3. System Requirements.
  4. Assumptions.
  5. How to install.
  6. How to invoke the class and pass parameter options.
  7. A list of parameter options supported by the class.
  8. Description of member functions.
  9. About the errors/warnings include file.
  10. Recommendations and things to watch out for.
  11. Known problems.
  12. Revision History.

Take a look at the readme file for quick installation steps.

Disclaimer/License

This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.     You should have received a copy of the GNU General Public License along with this program; if not, write to the:

Free Software Foundation, Inc.,
59 Temple Place, Suite 330,
Boston, MA 02111-1307 USA

Or you may obtain the license at
http://www.gnu.org/copyleft/gpl.html

 

Section 1 - Introduction.

This manual describes the use of a great custom PHP session handler class called DB_eSession. This free PHP class allows the storage of session data in a MySQL database rather than files (which is PHP's default). By storing PHP's session data in a database, it allows you to have better control of what information is stored, how it's retrieved or verified and makes for tighter security.

DB_eSession contains a lot of practical features designed for real world use where tougher security measures are essential. The class and its list of feature parameters may seem a little overwhelming at first glance, but it is really easy to use. Every field parameter has a set default, so you don't have to necessarily fill-in a value for every feature parameter to use the class. There is a table provided that describes each field parameter the class supports and its use.

This class includes member functions useful (to web masters) for monitoring/viewing, deleting, and altering sessions validity, like in the case of locking one or more sessions upon detection of unauthorized use. This custom PHP/MySQL database session handler class might just be what you're looking to implement on your web or intranet site.

You can use your browsers find command to search for what you're looking for in this manual. When you want to print this manual, it's best to choose the landscape mode with half inch margins all around.

Please feel free to send me an e-mail to register that you're using this class. That way, you will be notified if there's a new release of this class. Send e-mails to: code@dearneighbor.com

Thank you and enjoy,
Lawrence Osiris
http://www.code.dearneighbor.com

Back to the top of page

 

Section 2 - Features.

The DB_eSession class has the following list of features:

General features:

  • Stores session data in a MySQL table using PHP's built-in session handler.
  • Built-in handling of session expiration and cleanup.
  • Supports the changes of session related configuration settings (inc. PHP5).
  • Allows for normal or persistent MySQL database connections.
  • Access to opened MySQL resource connection to use in your script.
  • Accepts a passed database resource link to use as the DB connection.
  • Supports session ID's between 12 and 32 characters long.
  • Custom or changeable database, table and column names.
  • An option to create new session ID's (you supply, class or PHP builds).
  • Can initiate buffered output (using ob_start) within the class.
  • A session_start() automatically initiated within the class.
  • Can send 'Cache-Control:' header output within the class (fixes IE6 bug).
  • Ability to retrieve a specific sessions expiration date and time.
  • Retrieve current session life setting in seconds or minutes.
  • Retrieve a numeric total of the number of active and inactive sessions in table.
  • Facility to make assignment and retrieval of session variables easier.
  • Ability to create manual URI's and links that includes session name and ID.
  • The ability to retrieve what the MySQL server version number is.
  • An adequate form of encode/decode member functions are included and used automatically when libmcrypt is not installed.

Security features:

  • Standard user inactivity time-out handled automatically.
  • Absolute user logoff time-out capability (session will be terminated no matter what after a number of designated minutes/seconds have elapsed).
  • Ability to lock and unlock a particular session or all sessions. When a session is made locked it is immediately not available for use.
  • User to session verification using IP address and browser information.
  • Security level (code) clearance for each session/web page.
  • Encrypt/decrypt as desired each session field.
  • Encrypt/decrypt an extra session field to compare against original (to detect against possible tampering).
  • Encrypt/decrypt the whole session data in the table (essentially obscuring session variable names in table). Can be used in combination with per session field encryption, resulting in double encryption security.
  • A new encryption Initialization Vector is created every time values change.
  • Ability to manually delete a particular session or all sessions.
  • The users IP address and web browser is recorded as part of the session for tracing information.

Other features:

  • Support for multiple language error and warning messages.
  • Support of a default language as well as current active language settings.
  • Basic or detailed (with SQL syntax) error/warning reporting.
  • Buffered error and warning messages.
  • Option for class to stop execution or not upon encountering an error/warning. Class can display errors/warnings automatically or control in your script.
  • Can select font color and size separately for error and warning messages.
  • Code has lots of comments and formatted within 82 characters wide.
  • Full documentation (only provided in English) is included.
  • Code use examples provided, including a basic authentication (login/logout) process.
  • SQL text file provided for creating the MySQL session table.

Back to the top of page

 

Section 3 - System Requirements.

PHP version 4.2.0 or higher, MySQL version 3.22.5 or higher, web server (Apache, IIs), and Unix/Linux/Windows/Mac. An ability to create MySQL databases, usernames and passwords such as with phpMyAdmin. libmcrypt 2.2.x or higher is optional if you want to utilize encryption/decryption. The included sessEncode/sessDecode member functions will automatically be utilized when libmcrypt is not installed and encryption is requested. PHP's register_globals setting can be on or off, and the magic_quotes_runtime is automatically handled. The magic_quotes_gpc is checked but this class doesn't know if you will be trying to save session data coming straight from Get/Post/Cookie variables. This class by default will addslashes() to session data before saving, therefore it's best for you to stripslash() if necessary before hand. Session.auto_start needs to be off.

Back to the top of page

 

Section 4 - Assumptions.

This manual was written with the assumption that you know at least the basics of the PHP language and it's syntax. You don't have to be an expert, however, a good understanding of how to create and use variables (especially arrays) is essential. You don't need to know a lot about classes, but it would be enough to know how to create a new instance and reference them (there's examples given in this manual and the example files included). You should be able to know how to create PHP text files and upload/install them onto your server or web host provider, and be able to set the correct file permissions if necessary. There's no need to know about PHP's session mechanism but a general understanding of what sessions are for would be useful. The class takes care of the SQL queries, so there's really no particular need to know MySQL or SQL syntax, but knowing the basics would be helpful. It is at least required that you know how to create a MySQL database, table, a username, and password using any of the tools at your disposal (such as phpMyAdmin). Only the SQL to create the MySQL session table is included.

Back to the top of page

 

Section 5 - How to Install.

If you downloaded the compressed file, then you'll need to uncompress the file to reveal/extract all the individual files contained within it. You can use the tar command with the '--extract' option for Unix/Linux type of systems, WinZip for Windows, or StuffIt (Standard Edition Trial Version) for the Macintosh (which will uncompress the Windows zipped file under the Mac). Please refer to these tools manuals for how to extract the necessary files out of the compressed file.

Use phpMyAdmin or similar tool to create a MySQL database, username and password. If you already have these defined/setup, then you can use these if you wish instead of creating new ones. For security reasons, it is recommended for you to create a separate database, a restricted username, and password just for the sessions processing. If an unauthorized intruder gained access to the sessions database, then they will hopefully only have access to the sessions table, while your application related tables are perhaps protected by being in another database under a different username and password. Use the SQL within the included 'eSessions_table.sql' text file to create the sessions table (using phpMyAdmin). Then don't forget to update the 'config.DB_eSessions.php' file (discussed below) with the name of the local host, database, username, password, table name, and column names if they are different than the supplied defaults.

There are two required PHP files needed for a successful installation and one optional configuration file. The main PHP class  file is called 'class.DB_eSession.php'. This class requires an errors include file which comes with the package and is called 'errors.DB_eSession.php' by default. The third and optional configuration file is called 'config.DB_eSession.php'. This is not required by the class, but is made available to you for placing along with the scripts you write. It's recommended you keep the same naming conventions, that way all your class, configuration, and error files will be grouped together when viewing your directory listing (where the files are contained).

Before installing these files you might want to think about how you should organize your application directories on the web server. The files that come with this package do not need to be in the public web directory. It's actually best to keep them off the public web directory for security reasons. You only need to place the script(s) that the user interacts with in the public web directory, and have those scripts point to the directory where the other include files are stored. Let's go through an example. Say we have a root path of /home/user and a public web directory path of /home/user/www. One approach would be to create a PHP folder/directory used as a repository to hold all the files (such as those included in this package) that should be protected or just generally not needed in the public web directory area. You could call it something like 'php' or 'phplib' and create it in the user root area (i.e. /home/user/phplib).

Then in your script, specify a relative or absolute path when using the include or require commands. In the following example it is assumed that the script is running from the /home/user/www public web directory:

    <?PHP
    require_once('../phplib/config.DB_eSession.php');                   // Relative path example
    require_once('/home/user/phplib/class.DB_eSession.php');   // Absolute path example

    ?>

Another option is to specify all the various paths you have into the 'include_path' configuration setting. This causes PHP to search in all the directories specified for the file that you're trying to include/require. If you can't change the paths in your php.ini file, then you'll have to set the 'include_path' in every script that uses an include/require. Below is an example of how to change the 'include_path' configuration setting from within a PHP script:

    <?PHP
    // Example of a script running from the public web directory

    $ROOT_PATH = $_SERVER['DOCUMENT_ROOT']; // i.e. /home/user/www

    // Remove the last node directory from the path, which will leave
    // us with the private root path (i.e. /home/user)
    $PRIVATE_PATH = substr_replace($ROOT_PATH, '', strrpos($ROOT_PATH, '/'));

    $PHPLIB_PATH = $PRIVATE_PATH . '/phplib'; // i.e. /home/user/phplib

    // Can define other private directories such as for storing other files
    $DATA_PATH = $PRIVATE_PATH . '/data';     // i.e. /home/user/data

    // Combine all the paths and separate with a colon
    $PATHS = $PHPLIB_PATH . ':' . $DATA_PATH;

    // Set the search path for all the directories desired
    ini_set('include_path', (ini_get('include_path') . ':' . $PATHS));

    // Now there is no need to specify any paths in the include/require in the rest of your script
    require_once('config.DB_eSession.php');     // no need to specify a path; PHP will search for it
    require_once('class.DB_eSession.php');       // no need to specify a path; PHP will search for it

    ?>

The above code could be put in your own 'config' file and placed in the public web directory with your application script. Your application script can simply include the config file without specifying any paths since the config file is in the same directory as your application script. Optionally, you can also add the creation of the new instance of the class in your application config file. Below is an example of how the start of your /home/user/www/index.php script could look like:

    <?PHP
    // config.index.php sets include paths, and pulls in the config.DB_eSession and class.DB_eSession files
    require_once('config.index.php');                                 // In same the directory; no need to specify a path
    $sess_param['errors_path'] = '';                                    // For errors file; Don't specify a path since 'include_path' is set
    $sess_param['errors_file'] = 'errors.DB_eSession'// For errors file; Don't specify '.php' at the end
    $sess = new DB_eSession(&$sess_param);             // Create an instance of the class and pass by reference

    echo $sess->getVersion;                                              // Display class version number

    ?>

This class also uses an error include file called 'errors.DB_eSession.php' which is specified by setting the 'errors_path' and 'errors_file' parameter options. You can call this file something else, but it must be saved with '.php' at the end. When specifying 'errors_file' parameter, don't include the '.php' at the end of the filename because the class will add that automatically. For security reasons it is highly recommended that all your PHP scripts end with '.php' no matter what they are (config, application scripts, errors, classes, etc.).

After modifying any necessary files (i.e. config or errors), the files need to be installed or uploaded to your web server or web host provider (for uploading use an FTP software tool).

Here is an example of how your files could be organized after an upload:

    /home

      /user

        /data
             (for illustration purposes only - not required by class)

        /phplib
             class.DB_eSession.php
             config.DB_eSession.php
             errors.DB_eSession.php

        /www
             config.index.php
             index.php

Back to the top of page

 

Section 6 - How to invoke the class and pass parameter options.

You need to create a new instance of the class right at the beginning of your PHP script(s) (or at least before you send any output to the browser). You can have other include files first (before 'class.DB_eSession.php'). Again, just make sure there are no output sent to the browser before the creation of the DB_eSession instance, otherwise PHP will give you a 'headers already sent' error message. If you get this error, remove all whitespaces from include files or any echo/print commands invoked before creating an instance of the DB_eSession class. There can't be any whitespaces before the '<?PHP' at the start of your script or in include files. There also can't be any whitespaces after '?>' at the end of your script or in include files. If you're still getting this error after checking and fixing all your script/include files, then you will have to use PHP's output buffering option. This can be easily accomplished by passing the 'buffer' parameter set as TRUE to the DB_eSession class. The class will then know to invoke the PHP ob_start() function.

Make sure that the main class include file is placed at the top of your script(s) (see suggestions supplied in Section 5 - How to Install). The class can be invoked in three different ways. The easiest way is without passing any parameter options. But this only will work if you created the MySQL database, table, username, and password the same as the defaults defined in this class (see list of parameter options section). Below is an example of how to invoke a new instance of the class without passing any parameters:

    <?PHP
    require_once('class.DB_eSession.php');
    $sess = new DB_eSession;

    ?>

The second way is by passing a non-variable associative array of parameters defining the options you would like changed. Below is an example of that:

    <?PHP
    require_once('class.DB_eSession.php');
    $sess = new DB_eSession(array('db_host' => 'localhost',
                                                               'db_user' => 'sess_user',
                                                               'db_pswd' => 'sess1234',
                                                               'db_name' => 'db_esessions',
                                                               'tb_name' => 'eSessions'
                                                            
    )
                                                   );

    ?>

The third and most recommended way is by using an associative array variable. You can create your own variable or use the supplied configuration file like in the following example:

    <?PHP
    require_once('config.DB_eSession.php');
    require_once(
    'class.DB_eSession.php');
    $sess = new DB_eSession(&$sess_param);

    ?>

The $sess_param associative array variable is defined in the 'config.DB_eSession.php' file and it's passed as an input/argument to the DB_eSession class. You could have one main configuration file (recommended) that is used by all your scripts or you could have many. If you need to change an option for a particular script, you could override the configuration file setting by specifying that after the configuration include and before the creation of the new instance, like this:

    <?PHP
    require_once('config.DB_eSession.php');
    require_once(
    'class.DB_eSession.php');
    $sess_param['buffer'] = TRUE;
    $sess = new DB_eSession(&$sess_param);

    ?>

The output buffering option is normally set to FALSE (off) in the configuration file, so the above example is turning it on (TRUE) before the class instance is invoked.

Back to the top of page

 

Section 7 - A list of parameter options supported by the class.

Below is a table containing a list of all the various parameter options this class supports. The 'Array Key Name' column is the name of the key used in the associative array passed when creating an instance of DB_eSession class. For example:
$sess_param['stop_on_warn'] = TRUE;
$sess = new DB_eSession(&$sess_param);

This class supports the setting of Session Runtime Configuration options. Note that not all Session Runtime Configurations can be set or take effect outside of the php.ini configuration file. Some options can be set at runtime without an error produced, but have no effect. (i.e. session.auto_start). All session options are used here in case there is future support to make an option take effect at runtime (i.e. session.use_trans_sid). Don't add the 'session.' part to the array key because the class automatically adds that. For configuration option details, see: http://us2.php.net/manual/en/ref.session.php.

The 'R/O' column means whether the parameter is Required or Optional. Required means that it is most likely that you might want to change the value, to make it different than the class default, before creating an instance of the DB_eSession class.

Array Key Name

R/O

Description

Default Value

stop_on_error

R

Indicates to the class whether or not to stop execution of the script when it encounters a severe error. When this is set to TRUE, the class will automatically display all errors/warnings before stopping. When this is set to FALSE, the script will not stop, and it's up to you to check whether an error occurred and to display the error from within your script. There are three exceptions that you need to know about. The script will stop execution no matter what this setting is when the PHP version you're running is lower than the required version, or it could not open/find and include the errors file, or because the main setting of the session handler failed. It is recommend to leave as TRUE.

TRUE

stop_on_warn

O

Indicates to the class whether or not to stop execution of the script when it encounters a warning. When this is set to TRUE, the class will automatically display all warnings/errors before stopping. When this is set to FALSE, the script will not stop, and it's up to you to check whether a warning has occurred and to display the warning (if desired) from within your script. It is recommend that you turn this option on (TRUE) while developing and testing your site, and keep it turned off (FALSE) for the production or live site.

FALSE

session_start

O

When set TRUE it causes the class to issue the session_start(). When set FALSE, the session_start() must be performed within your script. However, a database connection is still established even when set FALSE so as to allow you to run the various maintenance type of member functions (like getAllSessInfo).

TRUE

buffer

O

The option to start buffering the output. You may want to use if you can't resolve the 'headers already sent' warning message generated by PHP and this class. The ob_end_flush() is called implicitly by PHP at the end of your script. It flushes out the contents of the buffer to the browser, and destroys the current output buffer.

FALSE

key_prefix

R

Set any arbitrary value for MD5 hashing keys. This key value is added at the beginning of obtained user information. It is used to hide and verify the users information (IP address and web browser details). Don't make it too long.

O9R^3mp#i|34

key_suffix

R

Set any arbitrary value for MD5 hashing keys. This key value is added at the end of obtained user information. It is used to hide and verify the users information (IP address and web browser details). Don't make it too long.

+t97!u0K-2L5

confirm_pswd

R

A password used to pass to the delete all sessions and lock/unlock member functions as a way to confirm the intent of modifying all the rows in the sessions table. Only required if you are going to call the member functions that use this.

!*CONFIRMED*!

encrypt

O

Whether or not to encrypt the whole session data. This basically encrypts and hides PHP's serialized session data, so not even the session variable names can be viewed in the MySQL table. The other included sessEncode/sessDecode memeber functions are automatically used if no mcrypt library is installed.

FALSE

encrypt_key

R

The key used to encrypt/decrypt individual field data or the whole session data. Keep this key a secret (and off the web directory). Use readable unique characters and make at least 62 characters long. The key default specified is made up of single unique characters of 0-9, a-z, and A-Z. This is required only if you plan on using any of the encryption member functions or 'encrypt' option.

z1Mc6KRxAfNwZ0dGj Y5qBXhtrPgJO7eCa UmHvQT3yW8nDsI2V kEpiS4blFoLu9

encrypt_cipher

O

This is used when encryption is desired and libmcrypt library is installed. Set to a valid encryption algorithm/cipher. If you have version 2.2.x of the library installed, then make sure that you select a cipher that is compatible with a newer (2.4.x) version too. This will prevent class decryption problems should you or your web host provider upgrade to a newer library (especially while there are active sessions still in table). MCRYPT_GOST is the default because it gave good benchmarks. See http://us4.php.net/mcrypt

MCRYPT_GOST

encrypt_mode

O

This is used when encryption is desired and libmcrypt library is installed. This class supports four block cipher modes : MCRYPT_MODE_ECB, MCRYPT_MODE_CBC, MCRYPT_MODE_CFB, MCRYPT_MODE_OFB. See http://us4.php.net/mcrypt

MCRYPT_MODE_CF B

db_host

R

Specify your MySQL host name. This usually is set to 'localhost' on most web host providers.

localhost

db_user

R

Specify the MySQL username that you created. This username must have been given permission to access the corresponding database.

sess_user

db_pswd

R

Your assigned password that belongs with the username created.

sess1234

db_name

R

Your MySQL database name.

db_esessions

db_persistent

R

MySQL database connection type; Normal or persistent. The default is for a normal connection (with a value of FALSE). Set to TRUE to have this class connect through a persistent connection. Persistent connections are resource links that do not close when your script ends. When a persistent connection is requested, PHP checks if there's already an identical persistent connection (that remained open from earlier) - and if it exists, it uses that. If it does not exist, it creates a new resource link. Note, that these kind of resource links only work if you are using a module version of PHP. See the PHP Persistent Database Connections manual section for more information.

FALSE

db_resource

R

Optionally supply a database resource link in the case where you have already established a connection with MySQL in your own script. When supplied, this class will not attempt to connect to MySQL and use the link you provide instead. This parameter overrides the 'db_persistent' option above. The default is NULL (resource not specified) which will make this class create a new connect to the MySQL server.

NULL

tb_name

R

The MySQL session table name that you created. It is called eSessions if you used the accompanying SQL to create the table.

eSessions

tb_id_col

R

The MySQL session ID column name which is the primary key in the table. It is called sess_id if you used the accompanying SQL to create the session table.

sess_id

tb_sl_col

R

The MySQL security level column name defined in the table. It is called sess_sec_level if you used the accompanying SQL to create the session table.

sess_sec_level

tb_cr_col

R

The MySQL session created column name defined in the table. It is called sess_created if you used the accompanying SQL to create the session table.

sess_created

tb_ex_col

R

The MySQL expiry column name defined in the table. It is called sess_expiry if you used the accompanying SQL to create the session table.

sess_expiry

tb_to_col

R

The MySQL session timeout column name defined in the table. It is called sess_timeout if you used the accompanying SQL to create the session table.

sess_timeout

tb_lk_col

R

The MySQL session locked column name defined in the table. It is called sess_locked if you used the accompanying SQL to create the session table.

sess_locked

tb_vl_col

R

The MySQL session data column name defined in the table. It is called sess_value if you used the accompanying SQL to create the session table.

sess_value

tb_iv_col

R

The MySQL session encryption initialization vector column name defined in the table. It is called sess_enc_iv if you used the accompanying SQL to create the session table.

sess_enc_iv

tb_si_col

R

The MySQL security ID column name defined in the table. It is called sess_sec_id if you used the accompanying SQL to create the session table.

sess_sec_id

tb_tr_col

R

The MySQL session trace column name defined in the table. It is called sess_trace if you used the accompanying SQL to create the session table.

sess_trace

security_level

R

Security Level: A numerical method to represent access authority for current session/web page. The lower the number means the higher the security clearance. In other words, security level 5 can only access all level 5 or higher session/web pages, and nothing lower than 5. The allowed range can be 0-255. The default is 128. For adminstration or sensative pages use 0 (zero) or 1 (one) as a value. For example: Set a member area page to 10, and an employee area page to 5. The employees will be able to access their own area, plus the members area. The members will be able to access their own area, but not the employee area because the security level number  required to access the employee area is lower. Members can only access any session/web pages with security level number of 10 or higher. Remember, a security level can't be changed after a session has been created. So, the first time the session is created with a set security level, that dictates the access authority for the rest of that active session.

 128

new_sid

O

Set to TRUE to force a new session ID to be created. Default is FALSE. It takes effect before a session_start(). This can be set TRUE without setting 'sess_id', in which case, a session ID will be automatically generated by the class/PHP. In the case of an authentication login/logout type of application, it's a good security measure to create a session only after the person has been authenticated and not before. It's even better, security wise, to force the creation of a new session ID after authentication, and this parameter option helps you do that. After being authenticated, set this parameter to TRUE before creating a session for the user.

FALSE

sess_id

O

Optionally set to a valid session ID you created. A valid session ID is made up of a-z, A-Z, 0-9, and should be the same length as specified in the 'sess_id_len' parameter option. Only works in conjunction with 'new_sid' option, which must be set to TRUE. The default is NULL (no custom session ID specified).

NULL

sess_id_len

O

Set to the length of the session ID desired. Must be between 12 and 32. The default is set to a 32 character session ID. It's highly recommended to keep at 32.

32

ie_fix

O

There is a form bug in Internet Explorer version 6 while using PHP sessions which causes the loss of filled-in information when returning to the form, after already leaving the form page (by any means). A work around is to use the HTTP 1.1 header "Cache-Control: private". It's set to TRUE (default) to send a header output to fix the IE bug.

TRUE

save_path

R

This is the 'session.save_path' configuration option. Set to the MySQL database name created.

db_esessions

name

O

This is the 'session.name' configuration option. For security reasons, it's recommended you use a different session name than PHP's default of PHPSESSID. Once set, don't change it for the life of the session. Defaults to eSESSION.

eSESSION

save_handler

O

This is the 'session.save_handler' configuration option. It's set to the default of 'user' to let PHP know that we're using a custom user specified session handler. Do not change it from 'user'.

user

auto_start

O

This is the 'session.auto_start' configuration option. specifies whether the session module starts a session automatically on request startup. No effect if changed at runtime. If you have auto start set on in the php.ini, then turn it off in order to use this class.

1

gc_probability

O

This is the 'session.gc_probability' configuration option. It's used to manage probability that the gc (garbage collection) routine is started. PHP's garbage collection default is 1. It's recommended you use at least 10 (which is the class default).

10

gc_divisor

O

This is the 'session.gc_divisor' configuration option. It defines the probability that the gc (garbage collection) process is started on every session initialization. The probability is calculated by using gc_probability/gc_divisor, e.g. 1/100 means there is a 1% chance that the GC process starts on each request.

100

gc_maxlifetime

R

This is the 'session.gc_maxlifetime' configuration option. Specifies the number of seconds of inactivity before the session will be considered as expired. i.e. 1440 seconds is 24 minutes. For security reasons, it is recommended to keep this value as small (short) as possible.

1440

timeout

R

As a security feature, there's an absolute session life timeout. This makes the session expire (no matter what) after a designated number of seconds have elapsed from the initial time of when the session was created. This helps in reducing the risk of session hijacking for extend periods of time. It is recommend that you don't set this value too high. Specify in seconds. It is defaulted to three times the value of gc_maxlifetime. i.e. 1440 (maxlifetime value) x 3 = 4320 seconds (72 minutes).

gc_maxlifetime * 3

serialize_handler

O

This is the 'session.serialize_handler' configuration option. It defines the name of the handler which is used to serialize and deserialize the data.

php

cookie_lifetime

O

This is the 'session.cookie_lifetime' configuration option. This specifies the maximum lifetime of the cookie in seconds which is sent to the browser. The value 0 means "until the browser is closed" (cookie will be deleted when user closes their browser). You could set this value to be the same as the 'timeout' option value. Which means as long as the session is within the time allowed, a user could close their browser and open it again to your site and the session should still be available for use/active.

0

cookie_path

O

This is the 'session.cookie_path' configuration option. This specifies the path to set in session_cookie when a cookie is created. See http://us2.php.net/manual/en/function.setcookie.php

'/'

cookie_domain

O

This is the 'session.cookie_domain' configuration option. This specifies the domain to set in session_cookie when a cookie is created. See http://us2.php.net/manual/en/function.setcookie.php

''

cookie_secure

O

This is the 'session.cookie_secure' configuration option. This specifies whether cookies should only be sent over secure connections. See http://us2.php.net/manual/en/function.setcookie.php. 1 = secure and 0 = non-secure. This class will produce a warning when this is set for secure (SSL) connections and the current web page is not secure (HTTP instead of HTTPS).

0

use_cookies

O

This is the 'session.use_cookies' configuration option. This specifies whether the module will use cookies to store the session id on the client side. 1 = enabled and 0 = disabled.

1

use_only_cookies

O

This is the 'session.use_only_cookies' configuration option. This specifies whether the module will only use cookies to store the session id on the client side. Defaults to 0 (disabled, for backward compatibility). Enabling (1) this setting prevents attacks involved in passing session ids in URLs. This setting was added in PHP 4.3.0.

0

referer_check

O

This is the 'session.referer_check' configuration option. This contains the substring you want to check each HTTP Referer for. If the Referer was sent by the client and the substring was not found, the embedded session id will be marked as invalid.

''

entropy_file

O

This is the 'session.entropy_file' configuration option. This gives a path to an external resource (file) which will be used as an additional entropy source in the session id creation process.

''

entropy_length

O

This is the 'session.entropy_length' configuration option. This specifies the number of bytes which will be read from the file specified in 'entropy_file'.

0

cache_limiter

O

This is the 'session.cache_limiter' configuration option. This specifies cache control method to use for session pages (none/nocache/private/private_no_expire/public). Defaults to nocache. See IE Fix and http://us2.php.net/manual/en/function.session-cache-limiter.php

nocache

cache_expire

O

This is the 'session.cache_expire' configuration option. This specifies time-to-live for cached session pages in minutes, this has no effect for nocache limiter.

180

bug_compat_42

O

This is the 'session.bug_compat_42' configuration option. PHP versions 4.2.0 and lower have an undocumented feature/bug that allows you to to initialize a session variable in the global scope, albeit register_globals is disabled. PHP 4.3.0 and later will warn you, if this feature is used, and if session.bug_compat_warn is also enabled

1

bug_compat_warn

O

This is the 'session.bug_compat_warn' configuration option. PHP versions 4.2.0 and lower have an undocumented feature/bug that allows you to to initialize a session variable in the global scope, albeit register_globals is disabled. PHP 4.3.0 and later will warn you, if this feature is used by enabling both session.bug_compat_42 and session.bug_compat_warn.

1

use_trans_sid

O

This is the 'session.use_trans_sid' configuration option. This specifies whether transparent sid support is enabled or not. 0 = disabled, 1 = enabled. The PHP manual states: URL based session management has additional security risks compared to cookie based session management. Users may send a URL that contains an active session ID to their friends by email or users may save a URL that contains a session ID to their bookmarks and access your site with the same session ID always, for example. This classes absolute timeout feature should take care of this security risk.

1

tags

O

This is the 'url_rewriter.tags' configuration option. This specifies which HTML tags are rewritten to include session id if transparent sid support is enabled.  Example: a=href,area=href,frame=src,form=,fieldset=. You might want to add the 'iframe=src' and the 'fieldset=' if it doesn't already contain it. You can use phpinfo() to see what it is currently set to.

Whatever your php.ini file sets it to.

hash_function

O

This is the 'session.hash_function' configuration option. This allows you to specify the hash algorithm used to generate the session IDs. 0 = MD5 (128 bits), 1 = SHA-1 (160 bits). This was introduced in PHP 5. It's best to keep at MD5 to be compatible with this class. SHA-1 has not been tested under this class.

0

hash_bits_per_character

O

This is the 'session.hash_bits_per_character' configuration option. This allows you to define how many bits are stored in each character when converting the binary hash data to something readable. The possible values are '4' (0-9, a-f), '5' (0-9, a-v), and '6' (0-9, a-z, A-Z, "-", ","). This was introduced in PHP 5. It's best to keep at '4' to be compatible with this class.

4

gc_del_locked

O

When set to TRUE, any locked session rows will be deleted right away, regardless of their current expiry or timeout settings when the Garbage Collection cleanup/delete member function is invoked. When FALSE, locked sessions will still be deleted but not until their expiry or timeout settings have expired first (which is the norm). The default is FALSE to allow a little time (depending on your gc_maxlifetime setting) to grab session trace information on locked sessions before they're deleted.

FALSE

slash_anyway

O

Set to TRUE to force addslashes() to occur on session data regardless of the magic quotes GPC option setting. Default is on (TRUE). If you find that data has slashes incorrectly, then turn this off (FALSE).

TRUE

strip_anyway

O

Set TRUE to force stripslashes() to occur on encrypted session data regardless of the magic quotes GPC option setting. The default is on (TRUE). If you find that data is saved incorrectly, then turn this off (FALSE).

TRUE

errors_path

R

Specify an absolute or relative directory path to where the errors and warning messag file can be located on your server.

./

errors_file

R

Specify the name of the error and warning message file. For security, specify a filename without the '.php' because the class will automatically add '.php' to the end of the filename.

errors.DB_eSession

default_lang

R

This is the default two character language code used as the associative array key for looking up error and warning messages. The class will use this default language code when it can't find an error/warning using the current language code setting (see below). This two character code must match the array key defined in the 'errors.DB_eSession.php' file. When an error/warning array entry can't be found, the associative array key is used as the error/warning letting you know there is an undefined error/warning that needs to be defined. The default is 'en' for English.

en

current_lang

O

This is the current two character language code used as the associative array key for looking up error and warning messages. Should your site support multiple languages, then when a user selects a particular language, change this value to match the current language desired. All supported languages must be previously defined within the 'errors.DB_eSession.php' file. When an error/warning can't be found using the current language code, then the default language code is used (see above).

First two characters of the value in: $_SERVER['HTTP_ACCEPT_LA NGUAGE']

detail_err_msgs

O

Set to TRUE to display SQL syntax and other values when displaying errors or warning messages encountered. The default is FALSE for security purposes, and that means actual values contained within errors/warnings will be replaced with X's. When the error is associated with an SQL problem, then the SQL error number and error message (not the SQL syntax) will be displayed regardless of this options setting. Turn it on mostly when in development or testing your site, but remember to turn it off for a production ready site.

FALSE

error_color

O

Specify a valid HTML color to display error messages in.

RED

error_size

O

Specify a valid HTML font size for displaying error messages in.

+0

warn_color

O

Specify a valid HTML color to display warning messages in.

BLUE

warn_size

O

Specify a valid HTML font size for displaying warning messages in.

+0

Back to the top of page

 

Section 8 - Description of member functions.

Below is a table that contains the name of each member function in the class, it's arguments, and a description of what it does. Member functions that start with an underscore are considered private and should not be called from your script.

Name of Function

Arguments

Description

DB_eSession

$_param = array()

This is the constructor which gets invoked when you create a new instance of the class in your script. No argument needs to be passed since the class sets defaults for everything.

When passing an argument it must be an associative array with the key/value pairs as described in Section 7's table. To save on memory you can pass the array variable by reference (the class does not change any of the values passed in the array). The constructor will stop the script if you have a PHP version less than the required minimum. It validates any passed key/value pairs and initializes all necessary variables that the class needs to use. This includes setting requested session configuration options. It checks to see if any headers have already been sent to the browser and produces a warning if that's the case. It sets the session handler to tell PHP to use the class member functions for session activity. It creates a new session ID when requested or necessary. It deletes any previous session if one existed. It creates or reestablishes an existing session by executing the session_start(). It sends the header to fix the IE bug (by default).

Any errors or warnings are displayed and script stops depending on the stop_on_error and stop_on_warn settings. If these settings are off, then you must check whether errors or warnings have occurred within your script (by calling errorsExist and warningsExist member functions) and act accordingly. The same process is the same for almost all the member functions within this class.

_formatFont

$_text,
$_color = 'BLACK',
$_size = '+0'

Formats the HTML font color and size attributes for the text that's passed to it. It's used to prepare error and warning messages.

_setErrMsg

$_errMsgKey = '',
$_SQL = NULL,
any number of additional arguments/values.

It uses the $_errMsgKey value and the current language code to look up the error message in the error array and adds the error message to the error buffer. When the error message is not found using the current language code, the default language code is used instead. Based on the detail errors option, It fills-in any additional passed values in order to produce a formatted error message. If the $_SQL value is passed, an SQL error number and message is added to the error message. When the detail errors option is set the SQL syntax ($_SQL value) is added to the error message.

_setWrnMsg

$_wrnMsgKey = '',
$_SQL = NULL,
any number of additional arguments/values

It uses the $_wrnMsgKey value and the current language code to look up the warning message in the warning array and adds the warning message to the warning buffer. When the warning message is not found using the current language code, the default language code is used instead. Based on the detail errors option, It fills-in any additional passed values in order to produce a formatted warning message. If the $_SQL value is passed, an SQL error number and message is added to the warning message. When the detail errors option is set the SQL syntax ($_SQL value) is added to the warning message.

_handleErrors

$_stop = FALSE

Detects if errors have occurred and displays any warnings or errors depending on the stop_on_error and stop_on_warn settings. The errors and warnings are in the color and size already set when the class instance was created. When applicable, any errors are always displayed before warnings. The script is stopped when the $_stop flag is set to stop (TRUE), or when there are errors/warnings and the stop_on_error or stop_on_warn settings are set to on (TRUE).

_setSessOption

$_config_option,
$_value,
$_check_sess = TRUE

Sets the value of the given session configuration option. When $_check_sess is TRUE, it checks to see if 'session.' is included in $_config_option and adds it if not there.

_genString

$_length = 0

Generates random characters from 1 to 32 in length. 32 characters is the default when length is not specified or not in the range of 1-32.

_setNewSessID

$_sess_id = NULL

This creates a new session ID or uses the session ID passed by you in 'sess_id'. Then it sets the session ID to make it ready for use. This is called before session_start() and before any output to the browser.

_getSecID

 

Creates an MD5 of a users trace information. Used to verify session belongs to same user. Not full-proof but adequate. Decided not to use HTTP_ACCEPT as part of the trace since results are inconsistent in IE6 (especially after a page refresh).

_getSessTrace

 

It creates a concatenated string of users trace information. Used for tracing IP address and other information in case of an unauthorized intruder. This information is saved in the 'sess_trace' column. The '~' is used as a delimiter to separate the different field values.

_sessDBOpen

$_save_path,
$_session_name

It connects and selects the MySQL database. It uses the database resource if one is passed to it, otherwise a persistent or normal connection is established based on the 'db_persistent' setting. It is automatically invoked by PHP upon the execution of a session_start().

_sessDBClose

 

Closes the connection to the database for non-persistent connections. It is automatically invoked by PHP when your script ends.

_sessDBRead

$_sess_id

This retrieves the session data from the table based on many parameters. The session data will not be found or used unless the session ID matches, the session is not locked, the security level is less than or equal to current security level, the session inactivity time hasn't expired, the session absolute timout hasn't expired, and the users information is the same (from _getSecID). If the data was selected to be encrypted when saved it will be automatically decrypted before use. It is automatically invoked by PHP upon the execution of a session_start().

 _sessDBWrite

$_sess_id,
$_sess_data

This inserts or updates the session data in the table. If the encryption option is on, the whole session data will be encrypted before being saved. When encryption is selected and PHP's magic quotes GPC option is on, or you elect to strip anyway, the stripslashes() function is perfomed on the whole session data. When the PHP magic quotes GPC option is off, or when you select to slash anyway, the addslashes() function is executed upon the session data. It is automatically invoked by PHP when your script ends.

 _sessDBDestroy

$_sess_id

Deletes session data from the table. It is automatically invoked by PHP when a session_destroy() is executed (in your script). For example: execute a session_destroy() after a user has choosen to log out.

_sessDBGC

$_maxlifetime

Deletes expired session data from the table. It deletes sessions that expire by the inactivity timeout, absolute timeout, or that are flagged as locked if the gc_del_locked setting is on. It is automatically invoked by PHP depending on the gc_probability configuration option settings.

getDBResource

 

Returns the current established MySQL resource link created in the _sessDBOpen member function. You might be able to use it in your script to access other tables, since a MySQL server connection has already been established for you. It's useful if you have other tables you want to access under the already selected database. Do not use this resource identifier to select a different database but open your own resource link instead, otherwise this session class may not work properly.

getSessInfo

$_sess_id = NULL,
$_full_exp = TRUE,
$_confirmation_pswd = NULL

This will return column information for the session ID passed. The current session ID is used when no session ID is passed. It returns an associative array with the table column names as the key.

The session data value, and encryption IV column values are returned only when a confirm password is passed. If the session value is encrypted, it will automatically be decrypted, however the session value data will be raw (in serialized format). If necessary, you can pass this serialized value to session_decode() to regenerate the session variables again.

The other columns retrieved are useful for determining when a session was created/started and when it will expire. If $_full_exp is FALSE, only the session ID is used to retrieve the row. When $_full_exp is left/set as TRUE the full expression is used as in _sessDBRead member function, but only if the $_sess_ID is the current session ID.

This function could return FALSE instead of an array, signifying an error has occurred or no data present.

getAllSessInfo

$_offset = 0,
$_row_count = -1,
$_order_by = NULL,
$_ascending = FALSE,
$_confirmation_pswd = NULL

This will return column information for all the session rows in the table. It returns a two dimensional associative array with the first index being the row number, and the second index is the table column names.

The session data value, and encryption IV column values are returned only when a confirm password is passed. If the session value is encrypted, it will automatically be decrypted, however the session value data will be raw (in serialized format). If necessary, you can pass this serialized value to session_decode() to regenerate the session variables again. The other columns retrieved are useful for determining when a session was created/started and when it will expire.

Set $_offset to the row number from where you would like MySQL to start retrieving the data from. The first row starts with 0 (zero). Set $_row_count to the number of rows of data you would like retrieved. A -1 (negative one) will cause MySQL to retrieve all the rows in the session table. You have a choice of having the data sorted by one column. Set $_order_by to a valid column name in the table. The data returned is sorted by the expiry column by default when no order by value is specified. Set $_ascending to TRUE to have the data sorted in ascending order (lowest to highest). When set FALSE (the default), the data will be sorted in descending order (highest to lowest).

For example: If the defaults are used, this will return all session rows in the table sorted by the expiry column in descending order, which will have the sessions that have recently expired or that are yet to expire returned first. To retrieve 20 rows at a time, you set $_row_count to 20 (during every call) and set $_offset to 0 (zero) on the first call, then on subsequent calls change the $_offset to 20, then 40, 60, 80, etc.

This function could return FALSE instead of an array, signifying an error has occurred or no data present.

getTableName

 

Returns the MySQL session table name.

getSessIDName

 

Returns the MySQL table column name for the session ID. This can be used as the key on the array returned by getSessInfo/getAllSessInfo to retrieve the columns value.

getSecLevelName

 

Returns the MySQL table column name for the security level. This can be used as the key on the array returned by getSessInfo/getAllSessInfo to retrieve the columns value.

getCreateName

 

Returns the MySQL table column name for the created epoch time. This can be used as the key on the array returned by getSessInfo/getAllSessInfo to retrieve the columns value.

getExpiryName

 

Returns the MySQL table column name for the expiry epoch. This can be used as the key on the array returned by getSessInfo/getAllSessInfo to retrieve the columns value.

getTimeoutName

 

Returns the MySQL table column name for the timeout epoch. This can be used as the key on the array returned by getSessInfo/getAllSessInfo to retrieve the columns value.

getLockName

 

Returns the MySQL table column name for the locked field. This can be used as the key on the array returned by getSessInfo/getAllSessInfo to retrieve the columns value.

getSessValueName

 

Returns the MySQL table column name for the sessions value field. This can be used as the key on the array returned by getSessInfo/getAllSessInfo to retrieve the columns value, but it will be in serialized form. If necessary, you can pass this serialized value to session_decode() to regenerate the session variables again.

getEncIVName

 

Returns the MySQL table column name for the encryption IV. This can be used as the key on the array returned by getSessInfo/getAllSessInfo to retrieve the columns value. The IV value is not very useful information by itself since the sessions data value is automatically decrypted before it's returned in the getSessInfo member function.

getSecIDName

 

Returns the MySQL table column name for the security ID. This can be used as the key on the array returned by getSessInfo/getAllSessInfo to retrieve the columns value. The security ID value is not very useful by itself since it's in md5 format.

getTraceName

 

Returns the MySQL table column name for the session trace. This can be used as the key on the array returned by getSessInfo/getAllSessInfo to retrieve the columns value.

nbrActiveSess

 

Returns a numeric value that designates the total number of active sessions currently in the table. An active session in this case means that the the session is not locked, the session inactivity time hasn't expired, and the session absolute timout hasn't expired.

nbrInactiveSess

 

Returns a numeric value that designates the total number of inactive sessions currently in the table. An inactive session in this case means that the the session is locked, or the session inactivity time has expired, or the session absolute timout has expired.

changeSessLock

$_sess_id,
$_lock_mode = FALSE

To lock or unlock a single session row in the table. When a session is locked, it will not be further read and is considered temporarily or permanently suspended. Must pass a valid session ID; no default assigned. You can use session_id() function to pass the current session ID.  When $_lock_mode is TRUE the session will be locked, otherwise it will be unlocked. It returns TRUE on a successful change or FALSE on error. Note: MySQL will not update columns where the updated value desired is the same as the current value in the table.

changeAllSessLocks

$_confirmation_pswd,
$_lock_mode = FALSE

To lock or unlock all session rows in the table. When a session is locked, it will not be further read and is considered temporarily or permanently suspended. Pass the confirm password to this member function as a way of making sure that it is your intention to lock/unlock all rows in the session table. When $_lock_mode is TRUE all sessions will be locked, otherwise all sessions will be unlocked. It returns TRUE on a successful change or FALSE on error. Note: MySQL will not update columns where the updated value desired is the same as the current value in the table.

deleteSession

$_sess_id

It is meant to be used to delete a single old/expired session row that may still be left in the table. Must pass a valid session ID; no default assigned. Do not use this to delete a current active session. But if you accidentally call it with the current active session ID, then the session_destroy() function is performed automatically instead. It returns TRUE on a successful delete and FALSE on error.

deleteAllSessions

$_confirmation_pswd = NULL

To delete all session rows from table. It's faster to drop and create the table again, however, the current database user should not have such security privileges. Pass the confirm password to this member function as a way of making sure that it is your intention to delete all rows from the session table. All rows will be deleted regardless of their expiration settings. In other words, any active sessions will be deleted too. It returns TRUE on a successful delete and FALSE on error.

pregMatches

$_pattern,
$_value

It checks $_pattern containing a regular expression against $_value and returns a boolean result. The preg_match result must match $_value for it to return a TRUE result. It uses a default pattern of '/[a-zA-Z0-9]+/' when no pattern is specified.

stringSplit

$_text,
$_chunksize = 1

Parses out a string ($_text) into $_chunksize number of byte chunk characters. Returns an array with each index containing $_chunksize characters. It's used in the sessEncode/sessDecode member functions, but left as a public member in case you have the need to use it too.

sessEncode

$_text,
$_IV = 3

Encodes plain text. Pass ($_IV) an Initialization Vector (IV) integer in the range of 1-500 in order to produce more varied results. You must use the same IV number when calling the sessDecode member. It returns the encoded text, which may be longer than original plain text. This member function uses the encrypt_key's value to encode. You should not change the encrypt_key's value for that reason (especially while there's active sessions in the table). This member function requires PHP ver >= 4.2.0 because of str_rot13 function (otherwise this class would only need ver >= 4.1.0).

sessDecode

$_text,
$_IV = 3

Decode text that was previously encoded with sessEncode member function. It returns the decoded text. Pass ($_IV) the same Initialization Vector (IV) integer as was used in the sessEncode member function. This member function uses the encrypt_key's value to decode. You should not change the encrypt_key's value for that reason (especially while there's active sessions in the table). This member function requires PHP ver >= 4.2.0 because of str_rot13 function. (otherwise this class would only need ver >= 4.1.0). Note that leading and trailing spaces will be deleted from the returned non-encrypted value.

sessEncrypt

$_text,
&$IV,
$_keep_open = FALSE

It encrypts plain text ($_text). You must pass a variable ($IV) by reference so that the Initialization Vector (IV) value can be returned. The same IV is needed for the decryption phase so it must be saved. The IV code is automatically saved for later decrypting when the encrypt setting is on, or you use the setSessVar member function with the encryption option.

It will first attempt to use the mcrypt algorithms if installed, otherwise the sessEncode member function is used. The encrypted text returned may be longer than the original plain text. It uses the encrypt_cipher and encrypt_mode settings to determine what type of encryption to use. It also uses the encrypt_key's value to encrypt. You should not change the encrypt_key's value for that reason (especially while there's active sessions in the table).

Set $_keep_open to TRUE when you have a few to many fields to encrypt in one script cycle, that way the mcrypt module will remain open to speed up encryption (but that only works for libmcrypt >= 2.4.x). It could return FALSE on encountering an error.

You can use this to encrypt data that you are storing in other databases/tables, but remember to store the IV as well.

sessDecrypt

$_enc,
$_IV,
$_keep_open = FALSE

Decrypts encrypted text ($_enc) created by the sessEncrypt member function. It needs to be passed ($_IV) the same Initialization Vector (IV) used in the encryption process.

It will use the sessDecode member function when the $_IV is in the range of 1-500, otherwise the mcrypt algorithms are used. It returns the original plain text. It uses the encrypt_cipher and encrypt_mode settings to determine what type of decryption to use. It also uses the encrypt_key's value to decrypt. You should not change the encrypt_key's value for that reason (especially while there's active sessions in the table).

Set $_keep_open to TRUE when you have a few to many fields to decrypt in one script cycle, that way the mcrypt module will remain open to speed up decryption (but that only works for libmcrypt >= 2.4.x). It could return FALSE on encountering an error. Note that leading and trailing spaces will be deleted from the returned non-encrypted value.

You can use this to decrypt data that you have stored in other databases/tables, but remember to use the same IV that was stored or used in the encryption phase.

sendCacheHeader

$_options = 'private'

Transmits the value of Cache-Control header option(s) passed to it. Always returns TRUE.

getMySQLVer

 

Returns the version number of the MySQL server.

getSessName

 

Returns the current class session name (equivalent to PHP's session_name() function).

getSessLife

$_in_minutes = FALSE

Returns the current PHP Session inactivity life duration in seconds (which is the gc_maxlifetime setting). Set $_in_minutes to TRUE to return the value in minutes (rounded up to the next whole minute).

getSessTimeout

$_in_minutes = FALSE

Returns the current PHP Session absolute life timeout duration in seconds (which is the timeout setting). Set $_in_minutes to TRUE to return the value in minutes (rounded up to the next whole minute).

setSessVar

$_field,
$_value = NULL,
$_encrypt_value = FALSE,
$_extra_field = FALSE,
$_ENC_SFX = '_enc',
$_ENC_IV_SFX = '_enc_iv',
$_ERROR = FALSE

This a very important and useful member function that you can use in your script to save the session data you want. Using $_field, it creates or updates a session variable's contents (with $_value). This is equivalent to simply doing: $_SESSION[$_field] = $_value; But there are more options available to you. You can even have $_value be an array to assign to $_field. The result value from an isSet() is returned which could be TRUE when set, or it could be FALSE if variable's value is NULL. If an error is encountered the return value to designate it's an error is left up to you by setting $_ERROR (which default's to FALSE).

You can select to have the session variables contents be encrypted by setting $_encrypt_value to TRUE. For extra security, you can select for an extra/duplicate field to be created (by setting $_extra_field to TRUE) which will contain the encrypted value (while leaving the non-encrypted value in the session field specified untouched/unchanged or non-encrypted). By using this option, getSessVar member function will automatically make a comparison of the two values for extra validity (to insure no hacker has changed the value). For the encryption option to work, $_value can't be an array, a boolean, a resource, or an object. To encrypt an array, you can always use the sessEncrypt member function on each individual array value.

When you select to have the value encrypted ($_encrypt_value is TRUE), a new session variable is created to hold the initialization vector (IV). The $_ENC_IV_SFX value is added at the end of the $_field value to come up with a new session variable name to hold the IV. Also, if you selected to have an extra field ($_extra_field is TRUE) there is another session variable created. The $_ENC_SFX value is added at the end of the $_field value to come up with a new session variable name to hold the encrypted value. Don't change the values of $_ENC_IV_SFX or $_ENC_SFX while there's active sessions still in the table.

For example: Let's say you pass 'password' in the $_field, and 'secret' as the $_value. A session variable of $_SESSION['password'] = 'secret' is created. If you elect to encrypt, then it would look something like: $_SESSION['password'] = 'xid9jdk3d', and another variable of $_SESSION['password_enc_iv'] = 'xkdjp20j34' is created as well. But if you selected that an extra field be created to hold the encrypted value instead, then this variable would be created: $_SESSION['password_enc'] = 'xid9jdk3d' while $_SESSION['password'] = 'secret' will contain the non-encrypted value. In either case the IV session variable is created.

Don't worry if you don't understand this process or it seems complicated, because everything is taken care of for you automatically (behind the scenes). For most common use, you simply pass the $_field and $_value of what you want saved (and maybe if you want it encrypted). This works in combination with the getSessVar member function.

getSessVar

$_field,
$_default = NULL,
$_ENC_SFX = '_enc',
$_ENC_IV_SFX = '_enc_iv',
$_ERROR = FALSE

This a very important and useful member function that you can use in your script to retrieve the session data you have saved off. It returns $_field session variables value if it has been previously assigned a value (other than NULL). You could have previously assigned the value yourself or used setSessVar member function.

If the session variable was not found or previously assigned, then the default value ($_default) is returned instead. The $_default value can be an array. If an error is encountered the return value to designate it's an error is left up to you by setting $_ERROR (which default's to FALSE).

But an error is only possible when trying to decrypt or during the extra field integrity check. Pass the same $_ENC_IV_SFX or $_ENC_SFX values that was used in setSessVar if you used something other than the defaults. Don't change the values of $_ENC_IV_SFX or $_ENC_SFX while there's active sessions still in the table. When a value is detected as encrypted, then the decrypted value will automatically be returned.

When the extra field option was selected when setSessVar was used, then an automatic comparison of the non-encrypted data is made against the extra field. If the variables values don't match, an $_ERROR is returned, and signifies a possible tampering of the session data.

Note that the $_SESSION array is only made available after a session_start() has occurred (like when you create an instance of this class).

stopOnWarnings

 

It sets to have the script stop when warning messages are generated within the class. This overrides the initial stop_on_warn setting. This is made available in case you want to turn on this option on a case by case basis within your script. Errors and warnings are printed by the class before execution is stopped.

endStopOnWarnings

 

It sets to have the script buffer any warning messages generated within the class and not have execution stopped. This overrides the initial stop_on_warn setting. This is made available in case you want to turn off warnings before calling a particular member function from within your script. With this being off, it's up to your script to handle displaying any warning messages and whether your script should stop execution.

warningsExist

 

It returns TRUE if warning messages have been generated within the class.

 flushWarnings

 

It returns NULL and clears/deletes all warning messages that may have been generated so far within the class.

 getWarnings

$_color = 'BLUE',
$_size = '+0'

It returns all warning messages for displaying in the $_color and $_size selected. It also clears the warnings buffer.

stopOnErrors

 

It sets to have the script stop when error messages are generated within the class. This overrides the initial stop_on_error setting. This is made available in case you want to turn on this option on a case by case basis within your script. Errors and warnings are printed by the class before execution is stopped.

endStopOnErrors

 

It sets to have the script buffer any error messages generated within the class and not have execution stopped. This overrides the initial stop_on_error setting. This is made available in case you want to turn off errors before calling a particular member function from within your script. With this being off, it's up to your script to handle displaying any error messages and whether your script should stop execution.

errorsExist

 

It returns TRUE if error messages have been generated within the class.

flushErrors

 

It returns NULL and clears/deletes all error messages that may have been generated so far within the class.

getErrors

$_color = 'RED',
$_size = '+0'

It returns all error messages for displaying in the $_color and $_size selected. It also clears the errors buffer.

setSessURI

$_uri

Appends the PHP session name and ID to the end of a URI. It checks whether a question mark already is in the URI. Useful for creating a URI to be used in a redirect (but less secure).

createSessLink

$_uri,
$_desc = NULL, $_target = NULL,
$_add_sess = TRUE

It returns a formatted link of $_uri and appends the PHP session name and ID when requested by setting $_add_sess to TRUE, which is the default. Pass the text description ($_desc) for the link, or the $_uri is used if none supplied. Optionally, pass any valid HTML target code of where to display upon link click. i.e. _blank opens a new window in the browser.

getIPAddr

&$type_used

It tries to detect and return the users IP address. You must pass a variable by reference so it can return a one character code to indicate what variable was used in retrieving the IP address. The $type_used returned could be either C, F, R, or U for HTTP_CLIENT_IP, HTTP_X_FORWARDED_FOR, REMOTE_ADDR, or it's unknown. If the value is obtained from HTTP_X_FORWARDED_FOR, it could have multiple IP addresses.

secureConnection

 

It returns TRUE if the current connection is secure (SSL) - using HTTPS.

getVersion

 

It returns the current version number of this DB_eSession class.

getSiteWarn

$_color = "NAVY",
$_size = '-2',
$_center = FALSE,
$_add_link = TRUE

It returns a formatted site warning message for displaying on your site. It uses the message in 'SITE_WARN' from the warning array ($_WRN) located in the errors.DB_eSession.php file. When $_add_link is TRUE and the warning message contains 'DB_eSession', it will convert that text to a link to the author's web site. You can specify the $_color and $_size of the font and whether it should be centered ($_center set to TRUE).

Back to the top of page

 

Section 9 - About the errors/warnings include file.

The 'errors.DB_eSession.php' file is used to define all the error and warning messages that this class needs. A two dimensional associative array is used to store the error messages, and another to store the warning messages. The first array index is an alphabetic code to identify the error/warning and it must not be changed because the class will be looking for these already predefined specific values. The second index of the array is a two character alphabetic code that identifies the language, and this can be changed to suit your needs. You must remember to assign the default language code and the current language code to match your error/warning language code definitions before creating an instance of the class. The error array variable name must be called $_ERR and the warning array variable name called $_WRN. For example:

$_ERR['SELECTDB_FAIL'] ['en'] = "Could not select MySQL database: %s\n";

$_WRN['NEW_SESS_ID']   ['en'] = "Assigning a new session ID.\n";

As part of the error/warning message there maybe strategically placed '%s' markers. These act as data place holders. The class will automatically replace these '%s' markers with actual values that pertain to the error/warning message. For example: in the 'SELECTDB_FAIL' error above, the '%s' will be replaced with the database name that it tried to select (if the detail error report setting is on, otherwise it will just show '[xxx]'). Leave these place holders, especially when creating error/warning messages in new languages.

To create messages in another language other than English, copy all the English errors and warnings and replace the 'en' value (the second index of the array) with another code, like 'fr' for French, 'gr' for German, or 'sp' for Spanish, etc. Then, translate each error and warning message into that language while leaving the data place holders ('%s') in the right places to coincide with the languages proper grammar. An example of how to create error and warning messages in another language is given inside the 'errors.DB_eSession.php' file. Note: The letter 's' used in the data place holder can be in upper or lower case.

Back to the top of page

 

Section 10 - Recommendations and things to watch out for.

In general, it's recommended to keep register_globals configuration setting off.

Change PHP's default
session name of PHPSESSID to something of your own. Then change it periodically (but not with active sessions still in the table).

Use the longest
length possible for session ID's to reduce prediction type of attacks.

For a login/logout system design, like in the case of a customer membership system, always create the session after the login. At times you may have the need to have a session created before or at the login page. Like to keep track of how many times they tried to login (and reject when too many failed attempts). In that case, generate a
new session after the login anyway, and discard the old session. Also, it's advisable to generate a picture graphic with letters and/or numbers for the user to enter during login. That way you know a human is trying to enter your site as opposed to a hacker using a script trying to break the password.

Make sure you provide a logout or delete/discard shopping cart function. As part of that functionality, you can then incorporate a
session destroy/delete feature.

Set
session expirations as short as feasibly possible.

Utilize fairly short absolute
session timeouts to prevent sessions from being active for long periods of time.

Encrypt any sensitive data stored in sessions (like passwords). You can
encrypt the whole session data or variable by variable using the setSessVar member function.

Use HTTP header information to verify that a
session belongs to requester which is done automatically for you in this class.

Only give the minimal privileges for a
username to access a database. Don't give all privileges like DROP access when SELECT, INSERT, UPDATE, and DELETE will do.

Keep as many files out of the public web directory as possible. Classes and configuration files (especially those containing passwords) should be kept at the root or non-public directory.

Use
passwords that are hard to predict and are not found in a standard dictionary. Use upper and lowercase letters, with numbers and symbols if allowed. Use different types of passwords and change them often.

Have E_NOTICE error_reporting() setting in effect while you test your scripts. It helps in identifying various problems in code including unassigned values, finding (variable) typos, and will warn you about bad style. Remember to remove the option in a production ready site.

Back to the top of page

 

Section 11 - Known Problems

When the 'stop_on_error' or 'stop_on_warn' parameter options are on, and an error/warning occurs within the class, the class will display the error/warning and stop the script. However, PHP might decide to display a warning message similar to the following as well:
Warning: Unknown(): A session is active. You cannot change the session module's ini settings at this time. in Unknown on line 0

There are a couple of bug reports posted regarding this. See: http://bugs.php.net/bug.php?id=26005 and http://bugs.php.net/bug.php?id=21306. The suggested fixes in these bug reports have not worked in my testing.

This warning seems to happen when the class does the exit, but not when the exit occurs outside of the class like within your script. Turning off warnings using error_reporting() does not get rid of this warning message either. This clearly indicates a PHP bug. If you should get this warning and you want to get rid of it, a workaround for now is to turn off 'stop_on_error' and 'stop_on_warn' options (which is before a new instance of the class is created), and check at strategic places for the errors and warnings from within your script. Like in this example:

if ($sess->errorsExist()) {
   echo $sess->getErrors();
   exit;
}

if ($sess->warningsExist()) {
   echo $sess->getWarnings();
   exit;
}
 

You can also use endStopOnErrors() and endStopOnWarnings() after a new instance of the class has been created to turn off errors and warnings from being generated from within the class.

Back to the top of page

 

Section 12 - Revision History

Revision 1.0.1 - June 3rd 2004:

The sessDecode member function sometimes truncated the last character. The bug had occurred  when all of the following conditions were met:

  • libmcrypt was not installed.
  • Using setSessVar with the encrypt option (which invoked sessEncode).
  • The text to be encrypted had even number of characters.

The problem was noticed when getSessVar was used to retrieve the text, which would contain one less character at the end. When the extra field option was used in setSessVar, then getSessVar returned FALSE.

This problem has been fixed in this release. The fix involved changing the last two lines in the sessDecode member function. The line that contained the substr() function was deleted, and a trim() was added to the return value.

These lines from sessDecode have changed from this:

       $_decoded = substr($_decoded, 0, -1);

       return $_decoded;
 

To simply this:

       return trim($_decoded);   // Rev 1.0.1: Added trim(). Removed substr().

Also, this manual was revised to include this revision section.
 

Revision 1.0.2 - August 8th 2004:

The sessDecode member function is missing an initialization line for the $_decoded variable. This may lead to unpredictable return value results.

The fix involved changing this area of code in sessDecode, from this:

       $_array = array_flip($_array);
       $_msgarr = $this->stringSplit($_text, 3);

       foreach ($_msgarr as $_mvalue) {

To this, which initializes $_decoded to an empty string:

       $_array = array_flip($_array);
       $_msgarr = $this->stringSplit($_text, 3);

       $_decoded = '';           // Rev 1.0.2: Added this initialization line

       foreach ($_msgarr as $_mvalue) {

Also, the $_SERVER['HTTP_ACCEPT_ENCODING'] value returned by Internet Explorer v6 was found not to be consistent especially when dealing with secure pages (HTTPS). Since this value was used as part of determining if it's the same user accessing the session, this could lead to the class not finding the same session table row. The fix was to simply comment out related code in the _getSecID() member function like this:

/* Rev 1.0.2: Found IE 6 to not return consistent results (under HTTPS)
       $_encoding = isSet($_SERVER['HTTP_ACCEPT_ENCODING']) ?
                           $_SERVER['HTTP_ACCEPT_ENCODING']  : 'NO ENCODING';
*/
       return md5($this->_KEY_PREFIX  .
                   $_IP                    .
                   $_type_used     .
                   $_agent             .
//***            $_encoding       .    Rev 1.0.2: Found as unreliable
                   $this->_KEY_SUFFIX
                 );
 

This manual was revised to include revision 1.0.2 details.

Back to the top of page

 

End of Manual.