I wrote the following code for a project I'm working on- it attempts to resolve the regenerate issue, as well as deal with a couple of other session related things.
I tried to make it a little more generic and usable (for instance, in the full version it throws different types of exceptions for the different types of session issues), so hopefully someone might find it useful.
<?php
function regenerateSession($reload = false)
{
if(!isset($_SESSION['nonce']) || $reload)
$_SESSION['nonce'] = md5(microtime(true));
if(!isset($_SESSION['IPaddress']) || $reload)
$_SESSION['IPaddress'] = $_SERVER['REMOTE_ADDR'];
if(!isset($_SESSION['userAgent']) || $reload)
$_SESSION['userAgent'] = $_SERVER['HTTP_USER_AGENT'];
$_SESSION['OBSOLETE'] = true;
$_SESSION['EXPIRES'] = time() + 60;
session_regenerate_id(false);
$newSession = session_id();
session_write_close();
session_id($newSession);
session_start();
unset($_SESSION['OBSOLETE']);
unset($_SESSION['EXPIRES']);
}
function checkSession()
{
try{
if($_SESSION['OBSOLETE'] && ($_SESSION['EXPIRES'] < time()))
throw new Exception('Attempt to use expired session.');
if(!is_numeric($_SESSION['user_id']))
throw new Exception('No session started.');
if($_SESSION['IPaddress'] != $_SERVER['REMOTE_ADDR'])
throw new Exception('IP Address mixmatch (possible session hijacking attempt).');
if($_SESSION['userAgent'] != $_SERVER['HTTP_USER_AGENT'])
throw new Exception('Useragent mixmatch (possible session hijacking attempt).');
if(!$this->loadUser($_SESSION['user_id']))
throw new Exception('Attempted to log in user that does not exist with ID: ' . $_SESSION['user_id']);
if(!$_SESSION['OBSOLETE'] && mt_rand(1, 100) == 1)
{
$this->regenerateSession();
}
return true;
}catch(Exception $e){
return false;
}
}
?>