How can PHP code be structured to avoid errors and improve readability when dealing with user login functionality?

To avoid errors and improve readability when dealing with user login functionality in PHP, it is essential to separate concerns by creating separate functions for different tasks such as validating user input, checking credentials, and handling session management. By structuring the code in a modular way, it becomes easier to debug, maintain, and understand the login functionality.

<?php

function validate_input($username, $password) {
    // Validate user input (e.g., check if fields are not empty)
}

function check_credentials($username, $password) {
    // Check if the provided credentials are valid (e.g., query the database)
}

function login_user($username) {
    // Start a session and set user data (e.g., user ID)
}

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $username = $_POST["username"];
    $password = $_POST["password"];

    validate_input($username, $password);
    if (check_credentials($username, $password)) {
        login_user($username);
        // Redirect or show success message
    } else {
        // Show error message
    }
}

?>