fixed up session class

This commit is contained in:
Nick Yeoman 2025-08-14 20:19:24 -07:00
parent 892110703b
commit 344786ee95

View File

@ -4,21 +4,27 @@ class Session {
private $session; private $session;
public function __construct() { public function __construct() {
if (session_status() === PHP_SESSION_NONE) {
session_start(); session_start();
if (!isset($_SESSION['token'])) {
$this->setToken();
$this->session['messages'] = [];
} else {
$this->session = $_SESSION;
} }
$this->session = &$_SESSION; // Reference $_SESSION to keep them in sync
if (!isset($this->session['token'])) {
$this->setToken();
}
if (!isset($this->session['messages'])) {
$this->session['messages'] = []; // Always ensure messages is an array
}
if (!isset($this->session['formData'])) {
$this->session['formData'] = []; // Initialize formData
}
if (!isset($this->session['errors'])) {
$this->session['errors'] = []; // Initialize errors
}
} }
public function setToken() { public function setToken() {
if (!isset($this->session['token'])) {
$this->session['token'] = bin2hex(random_bytes(32)); $this->session['token'] = bin2hex(random_bytes(32));
} }
}
public function set($key, $value) { public function set($key, $value) {
$this->session[$key] = $value; $this->session[$key] = $value;
@ -45,13 +51,13 @@ class Session {
} }
public function write() { public function write() {
$_SESSION = $this->session; // No need to assign to $_SESSION since $this->session is a reference
session_write_close(); session_write_close();
} }
public function kill() { public function kill() {
$this->session = [];
$_SESSION = []; $_SESSION = [];
session_destroy(); session_destroy();
} }
} }