What are the best practices for handling session management in PHP to ensure secure login/logout functionality?
To ensure secure login/logout functionality in PHP, it is important to properly handle session management. This includes using secure session handling functions, validating user input, implementing CSRF protection, and securely storing session data. By following best practices for session management, you can prevent unauthorized access to user accounts and protect sensitive information.
// Start session
session_start();
// Set session variables
$_SESSION['user_id'] = $user_id;
// Validate user input
if ($_POST['username'] == $valid_username && $_POST['password'] == $valid_password) {
// Successful login
} else {
// Failed login attempt
}
// Implement CSRF protection
if ($_POST['token'] === $_SESSION['token']) {
// Valid CSRF token
} else {
// Invalid CSRF token
}
// Securely store session data
$_SESSION['user_id'] = password_hash($user_id, PASSWORD_DEFAULT);
// Logout functionality
session_unset();
session_destroy();