How does the PHP code snippet provided handle user authentication and logout?

The PHP code snippet provided uses session variables to handle user authentication. When a user logs in, their username is stored in a session variable. When the user logs out, the session is destroyed, effectively logging the user out.

<?php
session_start();

// Check if user is logged in
if(isset($_SESSION['username'])) {
    echo 'Welcome, ' . $_SESSION['username'];
} else {
    echo 'Please log in';
}

// User login
if(isset($_POST['login'])) {
    $_SESSION['username'] = $_POST['username'];
}

// User logout
if(isset($_POST['logout'])) {
    session_destroy();
    header('Location: index.php');
}
?>

<form method="post">
    <input type="text" name="username" placeholder="Username">
    <input type="submit" name="login" value="Login">
    <input type="submit" name="logout" value="Logout">
</form>