What are common methods for implementing a login system in PHP?

Implementing a login system in PHP involves creating a form for users to input their credentials, validating those credentials against a database, and setting a session variable to keep the user logged in.

<?php
// Check if the form is submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Get the user input
    $username = $_POST["username"];
    $password = $_POST["password"];
    
    // Validate the user input (e.g. against a database)
    if ($username == "admin" && $password == "password") {
        // Set a session variable to keep the user logged in
        session_start();
        $_SESSION["username"] = $username;
        
        // Redirect to a protected page
        header("Location: protected_page.php");
        exit();
    } else {
        echo "Invalid username or password";
    }
}
?>