Skip to content

Instantly share code, notes, and snippets.

@glen-84
Last active December 16, 2015 17:28
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save glen-84/5470169 to your computer and use it in GitHub Desktop.
Save glen-84/5470169 to your computer and use it in GitHub Desktop.
Lazy session handler for ZF2
<?php
namespace Apex\Session;
use Zend\Session\SaveHandler\SaveHandlerInterface;
/**
* Based on https://github.com/adamfranco/lazy_sessions/blob/master/lazy_sessions.php
*
* @author Glen
*/
class LazySaveHandler implements SaveHandlerInterface
{
private $savePath;
/**
* Open Session - retrieve resources
*
* @param string $savePath
* @param string $name
*/
public function open($savePath, $name)
{
if ($savePath === '') {
$savePath = sys_get_temp_dir();
}
$this->savePath = $savePath;
if (!is_dir($this->savePath)) {
mkdir($this->savePath, 0777);
}
return true;
}
/**
* Close Session - free resources
*/
public function close()
{
return true;
}
/**
* Read session data
*
* @param string $id
*/
public function read($id)
{
$file = sprintf('%s/sess_%s', $this->savePath, $id);
// Handle the case of first time visitors and clients that don't store cookies (eg. web crawlers).
if (!isset($_COOKIE[session_name()])) {
return '';
}
if (file_exists($file) && ($data = file_get_contents($file)) !== false) {
return $data;
} else {
return '';
}
}
/**
* Write Session - commit data to resource
*
* @param string $id
* @param mixed $data
*/
public function write($id, $data)
{
if ($data === '') {
// Build up an array of cookie headers (excluding the session cookie).
$cookies = array();
foreach (headers_list() as $header) {
if (strpos($header, 'Set-Cookie') === 0 && strpos($header, 'Set-Cookie: ' . session_name()) !== 0) {
$cookies[] = $header;
}
}
// Remove all cookie headers.
header_remove('Set-Cookie');
// Add back non-session cookie headers (if any).
foreach ($cookies as $cookie) {
header($cookie);
}
return true;
}
$file = sprintf('%s/sess_%s', $this->savePath, $id);
return (file_put_contents($file, $data) !== false);
}
/**
* Destroy Session - remove data from resource for
* given session id
*
* @param string $id
*/
public function destroy($id)
{
$file = sprintf('%s/sess_%s', $this->savePath, $id);
if (file_exists($file)) {
unlink($file);
}
return true;
}
/**
* Garbage Collection - remove old session data older
* than $maxlifetime (in seconds)
*
* @param int $maxlifetime
*/
public function gc($maxlifetime)
{
foreach (glob(sprintf('%s/sess_*', $this->savePath)) as $file) {
if (filemtime($file) + $maxlifetime < time() && file_exists($file)) {
unlink($file);
}
}
return true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment