Session fixation and hijacking are serious security vulnerabilities that can lead to unauthorized access to user accounts. It's crucial to implement robust measures in PHP to prevent these attacks. Below are some practices that can help secure session management.
session.cookie_secure
directive to true
, ensuring cookies are only sent over HTTPS.session_regenerate_id(true)
to prevent attackers from using a pre-existing session ID.
<?php
// Start the session
session_start();
// Regenerate session ID to prevent fixation
session_regenerate_id(true);
// Set secure cookie parameters
session_set_cookie_params([
'lifetime' => 0,
'path' => '/',
'domain' => 'yourdomain.com',
'secure' => true, // Only send cookie over HTTPS
'httponly' => true, // JavaScript cannot access the session cookie
'samesite' => 'Strict' // Mitigate CSRF attacks
]);
// Store user information in session
$_SESSION['user_id'] = $user_id;
$_SESSION['ip_address'] = $_SERVER['REMOTE_ADDR'];
// Check for session hijacking
if ($_SESSION['ip_address'] !== $_SERVER['REMOTE_ADDR']) {
// Invalidate session
session_unset();
session_destroy();
echo 'Session has been hijacked, logged out.';
}
?>
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?