What are the best practices for structuring PHP code to handle user authentication and session management in a web application?

To handle user authentication and session management in a web application, it is best to use PHP sessions and securely store user credentials. This involves creating login and logout scripts, checking user credentials against a database, setting session variables upon successful login, and restricting access to certain pages based on session status.

// login.php
session_start();

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Check user credentials against database
    if ($valid_credentials) {
        $_SESSION["user_id"] = $user_id;
        header("Location: dashboard.php");
        exit();
    } else {
        echo "Invalid credentials";
    }
}

// logout.php
session_start();
session_unset();
session_destroy();
header("Location: login.php");
exit();

// dashboard.php
session_start();
if (!isset($_SESSION["user_id"])) {
    header("Location: login.php");
    exit();
}

// Other restricted pages
session_start();
if (!isset($_SESSION["user_id"])) {
    header("Location: login.php");
    exit();
}