How can a PHP script handle error messages for unsuccessful login attempts without exposing sensitive information in the URL?

To handle error messages for unsuccessful login attempts without exposing sensitive information in the URL, you can use sessions to store and display the error message. This way, the error message will not be visible in the URL and sensitive information will be kept secure.

<?php
session_start();

if($_SERVER["REQUEST_METHOD"] == "POST") {
    // Check login credentials
    if($login_successful) {
        // Redirect to dashboard
    } else {
        $_SESSION['error_message'] = "Invalid username or password";
        header("Location: login.php");
        exit();
    }
}

// In the login form or wherever you want to display the error message
if(isset($_SESSION['error_message'])) {
    echo $_SESSION['error_message'];
    unset($_SESSION['error_message']);
}
?>