PHP Classes

File: examples/sometimes.php

Recommend this page to a friend!
  Classes of Colin McKinnon   Stackable PHP Session Handler   examples/sometimes.php   Download  
File: examples/sometimes.php
Role: Example script
Content type: text/plain
Description: The writeSometimes handler (on top of the compatible handler)
Class: Stackable PHP Session Handler
Store session data with multiple session handlers
Author: By
Last change:
Date: 9 years ago
Size: 1,861 bytes
 

Contents

Class file image Download
<?php
require_once('utils.inc.php');
require_once(
'../handlers/stackSess.inc.php');
require_once(
'../handlers/compat.inc.php');
require_once(
'../handlers/writeSometimes.inc.php');

session_name('SESS_WS');

logger("started");
$storage=new compatSessionHandler();
$storage->setLogger('logger');
$handler=new writeSometimes($storage);
$handler->setLogger('logger');

if (!
$handler->install()) {
    print
"set handler failed";
    exit;
}
logger("* about to call session_start()");

session_start();
if (!isset(
$_SESSION['c'])) $_SESSION['c']=0;

if ((integer)
$_SESSION['c'] && !($_SESSION['c'] % 3)) {
   
logger("* about to regenerate");
   
session_regenerate_id();
}
if (
4>rand(0,10)) {
   
logger("*session changed");
    ++
$_SESSION['c'];
}
logger("about to finish");
session_write_close();
?>
<html>
<H1>The write Sometimes Handler</H1>
<p>
This handler only passes on writes to the lower layer if:
<ul>
<li>The session has changed</li>
<li>The session ID has changed</li>
<li>The session has reached 70% of its TTL</li>
</ul>
If you're only using your session to store information which changes
relatively infrequently (shopping basket, authentication) then this
can give a big boost to performance and capaciy. You're
unlikely to see much impact running a single instance on a lightly loaded
machine unless you've mounted your disks with <b>sync</b>.
</p><p>
Note that it must be layered on top of a storage handler.
</p><p>
While the other demos change the session each time, this only increments
the counter based on a throw of the dice so you see the effect of
omitting the write. That means it has 3 distinct behaviours:
<ul>
<li>no write</li>
<li>write session</li>
<li>write session with new session id</li>
</ul>
</p><p>
The logging output of the handler is shown below:<br />
<?php
print "OK:++\$_SESSION['c']=" . $_SESSION['c'] . "<pre>$statuslog</pre>";
exit;