BlueShoes Application Framework made with PHP http://www.blueshoes.org/


Packageindex Classtrees Modulegroups Elementlist Report XML Files

File: C:/usr/local/lib/php/blueshoes-4.2/core/net/http/session/Bs_SimpleSession.class.php
BlueShoes Application Framework - net/http/session

Bs_SimpleSession

Bs_Object
   |
  +-- Bs_SimpleSession

*************************************************************************************************

 

public class Bs_SimpleSession extends Bs_Object

*************************************************************************************************
Simple-Session Class.Extends PHP's standard session handling making it more usableFrom the PHP-manuel:"The session support allows you to register arbitrary numbers of variables to be preservedacross requests.When a visitor accesses your site, PHP will check automatically (ifsession.auto_start is set to 1) or on your request (explicitly through start() or implicitlythrough register()) whether a specific session id (SID) has been sent with the request. Ifthis is the case, the prior saved environment is recreated."Features :o Variables can be passed directly and do not have to be global.o Is only based on PHP's built in sessions handling, no additional SID is used.So we benefit from all features that PHP sessions handling uses to pass the SID(like url_rewriter.tags )o Automatically stores session data to disk when PHP exits.o Auto-change detection. If session-data is left unchanged, then no data is written to disk.o Supports garbage collecting.o Supports 'maxLifeTime' and 'maxStandbyTime'o 2do Protection against Session hijackingo You may have parallel sessions. You ask: "What are parallel sessions ?"the short answer is: "To have multiple session using *one* SID".Let me give you some examples in where you would like to have parallel sessions:1) You have 2 (or more) independent login pages on the same site and want to keep asession for each. Also you must guarantee that the same session vars are notoverwritten by accident.2) You would like to have a different timeout for some session-vars. E.g. Some pagesin a portal could be very conservative and would like to drop data while otherswould like to keep it until the browser is closed.3) You have to store a high volume of session data, but most of the data is NOT neededin every session. Using a normal PHP-session would load *all* session-vars collectedso far (if used or not). If the session data is complex (like serialized objects)this will result in a high overhead.Typical Use Cases:o You are programming object oriented and also think it's very 'dirty' to have to definethe session variables *global*. (See below "Reason for Writing this Class")o It's possible to have more then one session at a time (parallel sessions) and only thesession vars are loaded that are used. (See "Futures".)USAGE Samples################################################################################# Sample 1# --------# Simple Counter.include_once($APP['path']['core'] . 'net/http/Bs_SimpleSession.class.php');$session =& $GLOBALS['Bs_SimpleSession']; // Use the per ref operator '=&' <-- !!$aVariable=0;$ok = $session->register('my_var', $aVariable);if (!$ok) echo $session->getLastError();echo "<hr>Sample 1 - Simple Counter: <B>" . $aVariable++ . "</B><br>";################################################################################# Sample 2# --------# TIP: If you have a lot of session data that is not needed on every request, then# you may want to use following technique (called parallel sessions)# In this manner the $bigDataRec will only be loaded when needed and not on everyinclude_once($APP['path']['core'] . 'net/http/Bs_SimpleSession.class.php');$session =& $GLOBALS['Bs_SimpleSession']; // Use the per ref operator '=&' <-- !!$smallDataRec = NULL; // Data used in ever session$bigDataRec = NULL; // Data not used in ever session$session->register('my_sessionData', $smallDataRec);if ($needThatBigData) {$session->register('my_bigData', $bigDataRec, 'myBigDataSession');// do something with the $bigDataRec}// do something with the $smallDataReason for Writing this Class:In PHP you can only register variables that are global with PHP's session handling :-(.This is very unsatisfying when programming OO. So if I have a var $this->foo in an objectthat you would like to register with 'session_register()', you'd have to somehowglobalise it. *Yack!*This Class makes it much easier with a method like $session->register($key, $value).This class is called simple-session because :a) One main feature is the practical approach when working with PHP-objects. Session varsdon't have to be global (read below for more).b) Based on PHP's Session handling functions. This means that all the session features PHPare inherited like the use of cookies orBecause this object is based on the built-in session handling of PHP, all PHP sessionproperties set in php.ini also have an influence on this object. The most importantones are (Note: the defaults settings are usually OK):session.auto_start : Initialize session on request startup.session.use_cookies : specifies whether the module will use cookies to store the sessionid on the client side. Defaults to 1 (enabled).session.use_only_cookies: specifies whether the module will only use cookies to store thesession id on the client side.session.cookie_lifetime : (default 0 == "until restart of browser"). If a time >0 is given,all session data will be lost after that time is over.You can shorten this time in this class but NOT longer it.session.gc_maxlifetime : (default 1440 == 24min) defines how long after the last access thePHP-session should be considered as garbage. You can shorten thistime in this class but NOT longer it.variables order : (default "EGPCS") Describes the order in which PHP registers GET,POST and Cookie vars and therefore the order how PHP looks for the SID.NOTE: Check PHP-bug report: http://bugs.php.net/?id=14798 (PHP V4.1.0)Sessions lifetime will not work with Win and FAT32!For more info on PHP-session handling see http://www.zend.com/zend/tut/session.php and the PHP manuel.-----------------------------------------------------------------------------------------------------Implementation details:-----------------------Quite easy: We start a normal PHP sessions and only register one global variable called: $bs_sessInfoList$bs_sessInfoList is a hash and is brought into the Bs_SimpleSession object as$this->_sessInfoList. Every entry in $this->_sessInfoList represents a 'running' session.The session-entry is made of the property- and state-data.Session Info List ($this->_sessInfoList) :$_sessInfoList[<session name>] = array ('prop' => array ( // NOTE: Final values are given in constructor.'version' => 0, // <- Session version, to detect outdated session data if PHP sources change.'path' => "", // <- Path to where to store the session files.'maxStandbyTime' => 180, // <- How long should the session stay valid (in min) since last access. 0 means until browser end.'maxLifeTime' => 0, // <- Independent of use, invalidat after this time (in min). 0 means until browser end.),'state' => array ('SID' => $sid, // <- The unique SID for this session.'filePrefix' => $prefix, // <- The filename prefix (without path)'fileName' => $prefix . $sid,'createTime' => time(), // <- Time of creation (used with 'maxLifeTime')'accessTime' => time(), // <- Time of last access (used with 'maxStandbyTime')'md5' => '', // <- To autodetect changes.'forceWrite' => FALSE // <- To force a write to file (ignor autodetect)));During a session the $this->_sessInfoList is saved and read by PHP-session handling.And *no* other data is been imported (for the moment). We are now aware of the stateand property of all 'parallel' sessions and the source of it's data registered so far.Every session has a name that is the key in the _sessInfoList. All public function ofBs_SimpleSession have a last optional parameter called $sessName (default value = 'default').The moment you use one of these factions the data of $sessName is read. Or if it's a new sessionname a new _sessInfoList-entry is created. The data will automatically store at end of script.TO DO-----Prevent SID hijacking:If we reuse a previously created session by getting the sid from the querystring (and not from a cookie),we have a possible hole. Someone might send his url (with sid included) to someone else, and this personpastes it into the browser. See the problem. So what we do is check the class c network of the ip address(proxies might switch ip's).This still leaves room for ppl trading url's in the same company/using the same isp, but what can we do?Check browser string? hmm maybe. Well this is internal anyway and you shouldn't care.RECOMMENDATION: Please don't make use of the ini setting 'session.referer_check'.From the manual:contains the substring you want to check each HTTP Referer for. If theReferer was sent by the client and the substring was not found, theembedded session id will be marked as invalid. Defaults to the empty string.Reason:a) The referer can be cheated or change randomly (some privaty protectors do that).b) Now you're clever and add 'yourdomain.com'. Someone is on your site, opensanother webbrowser, clicks on a link to 'anotherdomain.com', which has a linkback to yourdomain.com. now what? right, session is lost, new one is created.and we don't want that, right?

Authors,
Version4.0.$id$
Copyrightblueshoes.org

 

Methods inherited from Bs_Object

isex, isexception, tostring, tohtml, persist, unpersist, bs_object, bbsetoutput, bbawake, bbisawake, bbxmsg, bbxfunctionstart, bbxfunctionend, bbxecho, bbxvar, bbxvardump, bbforcetrace, bbbufferstart, bbbufferget, bbbufferendflush, bbbufferendclean

Public Method Summary

bool

gc()

Garbage collection

Private Method Summary

void

&Bs_SimpleSession()

Constructor.
bool

start()

Starts up session.
void

register(string $key, string &$value, [ string $sessName ])

Register a var to the session
void

unRegister(string $key, [ string $sessName ])

Remove a var from the session register list
bool

isRegistered(string $key, [ string $sessName ])

Tells if the var is registered.
mixed

&getVar(string $key, [ string $sessName ])

Returns the value of a registered var.
bool

destroy([ string $sessName ])

Destroys all data of a session by removing the data.
bool

reset([ string $sessName ])

Reset the session data. All data is lost but session properties remain
void

setProperty(array $prop, [ string $sessName ])

Set a new property for a session.
void

getSid()

Returns the session id for the current session.
void

getLastError()

Returns the last error string.
void

write_close()

'Manually' store all session date to file.
void

_init( $sessName)

Internal init of a session.
void

_fetch( $sessName)

Fetch the data belonging to this session from the source.
void

_copyProp( $fromProp, &$toProp)

Copy property values from $fromProp to $toProp and do some checks
void

_pathCheck( &$path)

Standardize the passed path and check for existens and accessability.
void

_setup( $sessName)

Warning: documentation is missing.

Private Field Summary

array

$_sessInfoList

The vars that hold the session info.
array

$_sessPropTemplate

Helper vars
unknown

$this

string

$_sessStarted

array

$_sessData

string

$_sessPrefix

array

$_isValid

integer

$_souceVersion

string

$_lastError

Private Constant Summary

BS_SIMPLESESSION_VERSION >>4.0.$x$<< Warning: documentation is missing.

Public Method Details

gc

public bool gc( )

  Garbage collection
Old session files often have to be deleted. These orphan files are left overs ofuseres that for example just close theire browser. From time to time these orphanshave to be deleted.We parse all dir's we find in the _sessInfoList for files with the $this->_sessPrefixand read the modtime. If the age is greater then the APP['sess']['garbage_lifetime'](set in bs-conf file) the file is deleted.NOTE: This function is called randomly on every new session start. The %-chance to firea gc is given by $APP['sess']['gc'] (set in bs-conf file).

Returns bool

TRUE on success, FALSE otherwise

See Also getLastError()

Private Method Details

&Bs_SimpleSession

private void &Bs_SimpleSession( )

  Constructor.
There is no need to use this contructor. Please use the instance as follows$session =& $GLOBALS['Bs_SimpleSession']; (instead of $session =& new Bs_SimpleSession() )@pattern singleton

Returns void


start

private bool start( )

  Starts up session.
There is no need to call this function as Bs_SimpleSession is started the momentit's included (if not running already).

Returns bool

TRUE if succes, FALSE otherwise.


register

private void register( string $key, string &$value, [ string $sessName ] )

  Register a var to the session
by passing a unique key, the var and an optional session name.Behaver of this function:o If the passed key is *not* registered, the passed value is taken as default.o If the passed key is registered, the session value will overwrite the passed value(tis is possible because it's passed by reference)o From the moment you call register, that value is 'watched' (by holding a pointer to it).That means that any change to that value will be stored at the request end and availableat the next request.Sample I "Simple Counter":include_once($APP['path']['core'] . 'net/http/Bs_SimpleSession.class.php');$session =& $GLOBALS['Bs_SimpleSession']; // Use the per ref operator '=&' <-- !!$counter=0;if (!$session->register('my_counter', $counter)) echo $session->getLastError();echo $counter++ . "<br>";Sample II "Parallel Session":# TIP: If you have a lot of session data that is not needed on every request, then# you may want to use following technique (called parallel sessions)# In this manner the $bigDataRec will only be loaded when needed and not on everyinclude_once($APP['path']['core'] . 'net/http/Bs_SimpleSession.class.php');$session =& $GLOBALS['Bs_SimpleSession']; // Use the per ref operator '=&' <-- !!$smallDataRec = NULL; // Data used in ever session$bigDataRec = NULL; // Data not used in ever session$session->register('my_sessionData', $smallDataRec);if ($needThatBigData) {$session->register('my_bigData', $bigDataRec, 'myBigDataSession');// do something with the $bigDataRec}// do something with the $smallDataWARNING: Never add session values that reference themselfs in a cyclic way.PHP 4.x cycles 7 time and then ends. This will lead to unwanted results.E.g. $a = array(); $a[0] = &$a;Will become array(array(array(array(array(array(array()))))))Array of array, depth 7

Parameter
string $key
(to identify the value)
string &$value
(*by reference*)
string $sessName = >>'default'<<
(Optional, default is 'default'). Only used for parallel sessions.
Returns void

See Also register()

unRegister

private void unRegister( string $key, [ string $sessName ] )

  Remove a var from the session register list

Parameter
string $key
(to identify the value)
string $sessName = >>'default'<<
(Optional, default is 'default'). Only used for parallel sessions.
Returns void


isRegistered

private bool isRegistered( string $key, [ string $sessName ] )

  Tells if the var is registered.
The session-data with name == $sessName is loaded (if not loaded already)and checks if passed $key has a session value.TIP: Call only when you plan to use and/or modify a session var.This will improve the performance by omitting the file load.

Parameter
string $key
(to identify the value)
string $sessName = >>'default'<<
(Optional, default is 'default'). Only used for parallel sessions.
Returns bool


&getVar

private mixed &getVar( string $key, [ string $sessName ] )

  Returns the value of a registered var.
NOTE: You will normaly not be using this function. Instead you'll be using register().Examples:To get the data by value, do $val = getVar('someVar'); // Gives you a copyTo get the data by reference, do $ref = &getVar('someVar');

Parameter
string $key
(to identify the value)
string $sessName = >>'default'<<
(Optional, default is 'default'). Only used for parallel sessions.
Returns mixed

Throws NULL if not found of failer.

destroy

private bool destroy( [ string $sessName ] )

  Destroys all data of a session by removing the data.

Parameter
string $sessName = >>'default'<<
(Optional, default is 'default'). Only used for parallel sessions.
Returns bool

always TRUE.


reset

private bool reset( [ string $sessName ] )

  Reset the session data. All data is lost but session properties remain

Parameter
string $sessName = >>'default'<<
(Optional, default is 'default'). Only used for parallel sessions.
Returns bool

always TRUE.


setProperty

private void setProperty( array $prop, [ string $sessName ] )

  Set a new property for a session.
You may pass a property hash with following parameters. All are optionaland if omitet the default will be taken.$prop = array ('path' => "", // <- Path to where to store the session files.'maxStandbyTime' => 30, // <- How long should the session stay valid (in min) if *not* used. 0 means until browser end.'maxLifeTime' => 300, // <- Independent of use, invalidat after this time (im min). 0 means until browser end.);NOTE: 'maxLifeTime' is limited by PHP's 'session.cookie_lifetime' that we can not exceed ifcookies are used.PHP writes: "session.cookie_lifetime specifies the lifetime of the cookie in seconds which issent to the browser. The value 0 means "until the browser is closed." Default is 0."So session.cookie_lifetime == 0 is OK.

Parameter
array $prop
see above
string $sessName = >>'default'<<
(Optional, default is 'default'). Only used for parallel sessions.
Returns void


getSid

private void getSid( )

  Returns the session id for the current session.

Returns void


getLastError

private void getLastError( )

  Returns the last error string.

Returns void


write_close

private void write_close( )

  'Manually' store all session date to file.
Session data is atomatically stored after your script terminated without the need to call write_close(),but because we write the session-data with exclusive locks to prevent concurrent writes on the samefile this leads to a new behaver when sing framesets together with sessions. You will experiencethe frames loading one by one due to this locking. You can reduce the time needed to load allthe frames by ending the session as soon as all changes to session variables are done by callingwrite_close().

Returns void


_init

private void _init( $sessName )

  Internal init of a session.
Called at varius places in this code to insure that everthing has been set up OK.That's way we have to buffer the state.1) If already called befor, return the same state.2) If PHP session_start() hasn't been started, start now.3) If session with name '$sessName' is unknown, setup new session and GOTO END with status TRUE4) If PHP sources changed ('version') destroy and setup new session5) Check if a garbage collector need to start.6) If 'maxLifeTime' or 'maxStandbyTime' timed out GOTO END with status FALSE7) Try to fetch the session data form file. If we fail GOTO END with status FALSEEND)If status==TRUE : Update 'accessTime'.If status==FALSE: Try to destroy any old session andsetup a new one. Setup status is new status.Do: a) First try to fetch any valid session matches the session name.Dedata that check if a SID is already set and

Parameter
$sessName
Warning: documentation is missing.
Returns void


_fetch

private void _fetch( $sessName )

  Fetch the data belonging to this session from the source.

Parameter
$sessName
Warning: documentation is missing.
Returns void


_copyProp

private void _copyProp( $fromProp, &$toProp )

  Copy property values from $fromProp to $toProp and do some checks

Parameter
$fromProp
Warning: documentation is missing.
&$toProp
Warning: documentation is missing.
Returns void


_pathCheck

private void _pathCheck( &$path )

  Standardize the passed path and check for existens and accessability.
Trigger a PHP E_USER_WARNING on failer!

Parameter
&$path
Warning: documentation is missing.
Returns void


_setup

private void _setup( $sessName )

 

Warning: documentation is missing.

Parameter
$sessName
Warning: documentation is missing.
Returns void


Private Field Details

$_sessInfoList

private array $_sessInfoList

>>array()<<

The vars that hold the session info.


$_sessPropTemplate

private array $_sessPropTemplate

>>array ( // NOTE: Final values are given in constructor. 'version' => 0, // <- Session version, so we can detect outdated session data if PHP sources change. 'path' => "", // <- Path to where to store the session files. 'maxStandbyTime' => 180, // <- How long should the session stay valid (in min) if *not* used. 0 means until browser end. 'maxLifeTime' => 0, // <- Independent of use, invalidat after this time (im min). 0 means until browser end. )<<

Helper vars


$this

private unknown $this

>><<



$_sessStarted

private string $_sessStarted

>>NULL<<



$_sessData

private array $_sessData

>>array()<<



$_sessPrefix

private string $_sessPrefix

>>'bs_sess_'<<



$_isValid

private array $_isValid

>>array()<<



$_souceVersion

private integer $_souceVersion

>><<



$_lastError

private string $_lastError

>>""<<



Private Constant Details

BS_SIMPLESESSION_VERSION

define( BS_SIMPLESESSION_VERSION, >>4.0.$x$<< )
Case: default: case sensitive




Packageindex Classtrees Modulegroups Elementlist Report XML Files
PHPDoc 1.0beta