I have a method createSession() that calls session_regenerate_id(true); to prevent session fixation:
class Session {
public string $id;
public string $username;
public string $role;
public function __construct(){
session_start();
$this->id = $_SESSION['id'] ?? 0;
$this->role = $_SESSION['role'] ?? 'guest';
$this->username = $_SESSION['username'] ?? 'Guest User';
}
public function updateSession(array $user){
$this->createSession($user);
}
public function createSession(array $user){
session_regenerate_id(true);
$_SESSION['id'] = $user['id'];
$_SESSION['username'] = strstr($user['email'], '@', true);
$_SESSION['expire'] = time() + 30 * 60;
$_SESSION['role'] = $user['role'];
}
public function destroySession(){
$_SESSION = [];
$cookie_data = session_get_cookie_params();
setCookie(session_name(), '', time() - 42000, $cookie_data['path'], $cookie_data['domain'], $cookie_data['httponly']);
session_destroy();
}
}
After calling this function, all previous session data seems to be lost.
Is this behavior normal?
How can I securely regenerate the session without losing existing data?
Do I need to manually copy session values before regenerating?
I’m using PHP 8.2 and storing sessions in the default file-based handler. Could the session storage settings affect this ?