Skip to content

Instantly share code, notes, and snippets.

@u01jmg3
Created October 21, 2016 12:14
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save u01jmg3/b55645f70287fc8fc42f4184f716f577 to your computer and use it in GitHub Desktop.
Save u01jmg3/b55645f70287fc8fc42f4184f716f577 to your computer and use it in GitHub Desktop.
Session locking - non-blocking read-only sessions in PHP
<?php
function session_readonly(){
if(version_compare(PHP_VERSION, '7.0.0') >= 0){
session_start(array('read_and_close' => true));
} else {
$session_name = preg_replace('/[^\da-z]/i', '', $_COOKIE[session_name()]);
$session_data = file_get_contents(session_save_path() . '/sess_' . $session_name);
$return_data = array();
$offset = 0;
while($offset < strlen($session_data)){
if(!strstr(substr($session_data, $offset), '|')){
break;
}
$pos = strpos($session_data, '|', $offset);
$num = $pos - $offset;
$varname = substr($session_data, $offset, $num);
$offset += $num + 1;
$data = unserialize(substr($session_data, $offset));
$return_data[$varname] = $data;
$offset += strlen(serialize($data));
}
$_SESSION = $return_data;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment