How can PHP be used to validate form input and display error messages without clearing the input data?

When validating form input in PHP, it is important to display error messages without clearing the input data that the user has already entered. One way to achieve this is by storing the input data in session variables and displaying the error messages next to the corresponding input fields. This way, the user can see what data they entered incorrectly while still retaining their input.

<?php
session_start();

// Initialize variables for form input and error messages
$name = $email = $message = '';
$nameErr = $emailErr = $messageErr = '';

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Validate name
    if (empty($_POST["name"])) {
        $nameErr = "Name is required";
    } else {
        $name = test_input($_POST["name"]);
    }

    // Validate email
    if (empty($_POST["email"])) {
        $emailErr = "Email is required";
    } else {
        $email = test_input($_POST["email"]);
        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $emailErr = "Invalid email format";
        }
    }

    // Validate message
    if (empty($_POST["message"])) {
        $messageErr = "Message is required";
    } else {
        $message = test_input($_POST["message"]);
    }

    // Store input data in session variables
    $_SESSION['name'] = $name;
    $_SESSION['email'] = $email;
    $_SESSION['message'] = $message;

    // Redirect to the form page to display error messages
    header("Location: form.php");
    exit();
}

function test_input($data) {
    $data = trim($data);
    $data = stripslashes($data);
    $data = htmlspecialchars($data);
    return $data;
}
?>