How can sessions be used to handle login/logout functionality in PHP?
Sessions can be used to handle login/logout functionality in PHP by storing the user's login status in a session variable. When a user logs in, set a session variable to indicate that the user is authenticated. When the user logs out, unset the session variable to indicate that the user is no longer authenticated.
// Start the session
session_start();
// Check if the user is logged in
if(isset($_SESSION['logged_in']) && $_SESSION['logged_in'] === true) {
echo "User is logged in.";
} else {
echo "User is not logged in.";
}
// Log the user in
$_SESSION['logged_in'] = true;
// Log the user out
unset($_SESSION['logged_in']);