Home » HTTP » HTTP_Session2 » Manual
The HTTP_Session2 package provides an Object-oriented interface to the session_* family functions. It's a PHP5 port of the HTTP_Session package. HTTP_Session2 provides extra features such as database storage for session data using the DB and MDB2 package. It also introduces new methods, such as isNew(), useCookies(), setExpire(), setIdle(), isExpired(), isIdled() and others.
Introduction
Introduction – An introduction to HTTP_Session2
Overview
This package provides access to session-state values as well as session-level settings and lifetime management methods.
Based on the standart PHP session handling mechanism HTTP_Session2 provides more advanced features such as database containers, idle and expire timeouts and more.
A few examples
Setting options and detecting a new session
<?php
HTTP_Session2::useCookies(false);
HTTP_Session2::start('MySessionID');
HTTP_Session2::set('variable', 'The string');
if (HTTP_Session2::isNew()) {
echo 'new session was created with the current request';
$visitors++; // Increase visitors count
}
// continue
?>
Setting timeouts
<?php
HTTP_Session2::start();
HTTP_Session2::setExpire(time() + 60 * 60); // expires in one hour
HTTP_Session2::setIdle(time() + 10 * 60); // idles in ten minutes
// the session expired
if (HTTP_Session2::isExpired()) {
echo 'Your session has expired!';
HTTP_Session2::destroy();
}
// the session is idle
if (HTTP_Session2::isIdle()) {
echo "You've been idle for too long!";
HTTP_Session2::destroy();
}
HTTP_Session2::updateIdle();
?>
For a more comprehensive example of persistent sessions, please check the cookie section.
Using a database container
Using a database container – How to store session data in a database with HTTP_Session2
Overview
HTTP_Session lets you store the session data in a database making use of the DB and MDB2 packages.
Example
Using MDB2 to store session data in a database
<?php
/* create the following table in your database
CREATE TABLE sessiondata (
id varchar(32) NOT NULL,
expiry int(10),
data text,
PRIMARY KEY (id)
);
*/
require_once 'HTTP/Session2.php';
HTTP_Session2::useTransSID(false);
HTTP_Session2::useCookies(false);
// enter your DSN
HTTP_Session2::setContainer('MDB2',
array('dsn' => 'mysql://root:password@localhost/database',
'table' => 'sessiondata'));
/*
// using an existing MDB2 connection
HTTP_Session2::setContainer('MDB2',
array('dsn' => &$db, 'table' => 'sessiondata'));
*/
HTTP_Session2::start('s');
HTTP_Session2::setExpire(time() + 60); // set expire to 60 seconds
HTTP_Session2::setIdle(time() + 5); // set idle to 5 seconds
if (HTTP_Session2::isExpired()) {
HTTP_Session2::destroy();
}
if (HTTP_Session2::isIdle()) {
HTTP_Session2::destroy();
}
HTTP_Session2::updateIdle();
?>