How can history navigation be properly handled in PHP to display error messages or revert to previous pages based on certain conditions?

When handling history navigation in PHP, you can use sessions to store error messages or previous page URLs. If a certain condition is met (e.g., an error occurs), you can redirect the user back to the previous page or display an error message. Here's a PHP code snippet to demonstrate this:

session_start();

// Check if an error condition is met
if ($error_condition) {
    $_SESSION['error_message'] = "An error occurred.";
    header("Location: {$_SERVER['HTTP_REFERER']}");
    exit();
}

// Display error message if set
if (isset($_SESSION['error_message'])) {
    echo $_SESSION['error_message'];
    unset($_SESSION['error_message']);
}