How can PHP be used to display flash messages to users after a successful login or error message?

To display flash messages to users after a successful login or error message in PHP, you can use session variables to store the message and then display it on the next page load. After setting the message in the session variable, you can redirect the user to the desired page where the message will be displayed.

// Set flash message for successful login
$_SESSION['success_message'] = "Login successful! Welcome back.";

// Set flash message for error
$_SESSION['error_message'] = "Invalid username or password.";

// Redirect to the desired page
header("Location: index.php");
exit();
```

On the page where you want to display the flash message, you can check if the session variable is set and display the message accordingly.

```php
// Display success message
if(isset($_SESSION['success_message'])) {
    echo '<div class="success-message">' . $_SESSION['success_message'] . '</div>';
    unset($_SESSION['success_message']);
}

// Display error message
if(isset($_SESSION['error_message'])) {
    echo '<div class="error-message">' . $_SESSION['error_message'] . '</div>';
    unset($_SESSION['error_message']);
}