PHP
Strengthen PHP Session Security Practices
Enhance PHP session security by implementing session regeneration, secure cookie flags, and proper session destruction to prevent session fixation and hijacking attacks.
<?php
// Start or resume a session with secure settings
function start_secure_session(): void {
ini_set('session.use_strict_mode', 1); // Prevent session fixation
ini_set('session.cookie_httponly', 1); // Prevent XSS from accessing session cookie
ini_set('session.cookie_secure', 1); // Only send cookie over HTTPS
ini_set('session.cookie_samesite', 'Lax'); // Mitigate CSRF (adjust to 'Strict' if appropriate)
session_start();
// Regenerate session ID periodically and after privilege changes (e.g., login)
if (!isset($_SESSION['LAST_ACTIVITY'])) {
$_SESSION['LAST_ACTIVITY'] = time();
session_regenerate_id(true); // Regenerate ID and delete old session file
} else if (time() - $_SESSION['LAST_ACTIVITY'] > 300) { // 5 minutes inactivity timeout
session_regenerate_id(true);
$_SESSION['LAST_ACTIVITY'] = time();
}
}
// Log out function
function logout_user(): void {
$_SESSION = []; // Clear session data
session_destroy(); // Destroy session
// Clear session cookie
if (ini_get("session.use_cookies")) {
$params = session_get_cookie_params();
setcookie(session_name(), '', time() - 42000,
$params["path"], $params["domain"],
$params["secure"], $params["httponly"]
);
}
}
// Usage example:
// start_secure_session();
// if (!isset($_SESSION['user_id'])) {
// // User not logged in
// $_SESSION['message'] = "Please log in.";
// } else {
// // User is logged in
// echo "Welcome back, user " . $_SESSION['user_id'] . "!
";
// }
//
// // Example of logging out
// // logout_user();
// // header("Location: /login.php"); exit();
?>
How it works: This snippet outlines best practices for securing PHP sessions. It starts by setting crucial `ini_set` directives for `session.use_strict_mode`, `session.cookie_httponly`, `session.cookie_secure`, and `session.cookie_samesite` to prevent session fixation, XSS cookie access, and ensure cookies are sent only over HTTPS while mitigating CSRF. It then demonstrates session ID regeneration upon initial access and periodically, which helps prevent session hijacking. The `logout_user` function ensures a complete and secure termination of the session by clearing data, destroying the session file, and invalidating the session cookie.