What are the best practices for binding session keys to IP addresses in PHP to prevent session hijacking risks?
To prevent session hijacking risks, it is recommended to bind session keys to IP addresses in PHP. This means that a session key will only be valid if it originates from the same IP address it was created on, making it more difficult for attackers to hijack sessions.
// Start the session
session_start();
// Check if the session IP matches the current user's IP
if (isset($_SESSION['session_ip']) && $_SESSION['session_ip'] !== $_SERVER['REMOTE_ADDR']) {
session_unset();
session_destroy();
// Redirect to login page or handle unauthorized access
}
// Bind the session key to the current user's IP address
$_SESSION['session_ip'] = $_SERVER['REMOTE_ADDR'];