What are the best practices for structuring PHP code for login authentication?

When structuring PHP code for login authentication, it is important to follow best practices to ensure security and efficiency. This includes using prepared statements to prevent SQL injection attacks, hashing passwords securely, and implementing proper error handling to provide informative feedback to users.

<?php
// Start a session
session_start();

// Check if the form was submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Validate input data
    $username = $_POST['username'];
    $password = $_POST['password'];

    // Hash the password
    $hashed_password = password_hash($password, PASSWORD_DEFAULT);

    // Perform database query to check if the user exists
    // Use prepared statements to prevent SQL injection
    $stmt = $pdo->prepare("SELECT * FROM users WHERE username = ?");
    $stmt->execute([$username]);
    $user = $stmt->fetch();

    // Verify password
    if ($user && password_verify($password, $user['password'])) {
        // Login successful, set session variables
        $_SESSION['user_id'] = $user['id'];
        $_SESSION['username'] = $user['username'];
        // Redirect to dashboard or home page
        header("Location: dashboard.php");
        exit();
    } else {
        // Invalid credentials, display error message
        $error = "Invalid username or password";
    }
}
?>