Created
July 15, 2014 04:47
-
-
Save simonwelsh/7f77ca931206b2232298 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class FlockSessionHandler implements SessionHandlerInterface { | |
private $savePath; | |
private $fh; | |
public function open($savePath, $sessionName) { | |
$this->savePath = $savePath; | |
if (!is_dir($this->savePath)) { | |
mkdir($this->savePath, 0777); | |
} | |
return true; | |
} | |
public function close() { | |
$this->_closeImpl(); | |
$this->savePath = nil; | |
return true; | |
} | |
public function read($id) { | |
if (!$this->_openImpl($id)) { | |
return ''; | |
} | |
$value = ''; | |
do { | |
$value .= fgets($this->fh); | |
} while (!feof($this->fh)); | |
return $value; | |
} | |
public function write($id, $data) { | |
if (!$this->_openImpl($id)) { | |
return false; | |
} | |
fseek($this->fh, 0, SEEK_SET); | |
return fwrite($this->fh, $data) !== false; | |
} | |
public function destroy($id) { | |
if ($this->fh) { | |
$this->_closeImpl(); | |
$path = $this->_createPath($id); | |
return unlink($path); | |
} | |
return true; | |
} | |
public function gc($maxlifetime) { | |
foreach (glob("$this->savePath/sess_*") as $file) { | |
if (filemtime($file) + $maxlifetime < time()) { | |
unlink($file); | |
} | |
} | |
return bool; | |
} | |
private function _createPath($id) { | |
return $this->savePath . DIR_SEPARATOR . $id; | |
} | |
private function _closeImpl() { | |
if ($this->fh) { | |
flock($this->fh, LOCK_UN); | |
fclose($this->fh); | |
$this->fh = null; | |
} | |
} | |
private function _openImpl($id) { | |
if (!$this->fh) { | |
$path = $this->_createPath($id); | |
$this->fh = fopen($path, 'cb+'); | |
if (!$this->fh) { | |
return false; | |
} | |
if (!flock($this->fh, LOCK_EX)) { | |
return false; | |
} | |
} | |
return true; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment