WizdomWeb/app/Utilities/SessionHelper.php

116 lines
2.6 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
/**
* File: SessionHelper.php
* Version: 1.1
* Path: /app/Utilities/SessionHelper.php
* Purpose: Utility to simplify session handling, especially flash messages.
* Project: Wizdom Networks Website
*/
namespace WizdomNetworks\WizeWeb\Utilities;
class SessionHelper
{
/**
* Start the PHP session if it hasnt been started yet.
*/
public static function start(): void
{
if (session_status() === PHP_SESSION_NONE) {
session_set_cookie_params([
'lifetime' => 0,
'path' => '/',
'domain' => $_SERVER['HTTP_HOST'], // <- ensures subdomain support
'secure' => true, // <- required for HTTPS
'httponly' => true,
'samesite' => 'Lax'
]);
session_start([
'cookie_secure' => true,
'cookie_httponly' => true,
'cookie_samesite' => 'Lax'
]);
Logger::info("Session started manually via SessionHelper.");
} else {
Logger::info("Session already active.");
}
Logger::info("Session status: " . session_status());
}
/**
* Set a session variable.
*
* @param string $key
* @param mixed $value
*/
public static function set(string $key, $value): void
{
$_SESSION[$key] = $value;
}
/**
* Get a session variable (does not unset).
*
* @param string $key
* @param mixed $default
* @return mixed
*/
public static function get(string $key, $default = null)
{
return $_SESSION[$key] ?? $default;
}
/**
* Get and remove a session flash variable.
*
* @param string $key
* @param mixed $default
* @return mixed
*/
public static function flash(string $key, $default = null)
{
$value = $_SESSION[$key] ?? $default;
unset($_SESSION[$key]);
return $value;
}
/**
* Check if a session key is set.
*
* @param string $key
* @return bool
*/
public static function has(string $key): bool
{
return isset($_SESSION[$key]);
}
/**
* Finalize the session and persist data to disk.
*
* @return void
*/
public static function writeClose(): void
{
if (session_status() === PHP_SESSION_ACTIVE) {
session_write_close();
Logger::info("✅ Session write closed via SessionHelper.");
}
}
/**
* Destroy the session and clear all session data.
*
* @return void
*/
public static function destroy(): void
{
if (session_status() === PHP_SESSION_ACTIVE) {
$_SESSION = [];
session_destroy();
Logger::info("Session destroyed via SessionHelper.");
}
}
}