What are common ways to handle form validation in PHP to prevent loss of input data?

When handling form validation in PHP, one common way to prevent loss of input data is to use client-side validation with JavaScript to catch errors before the form is submitted. This can help improve user experience by providing instant feedback on invalid inputs. Additionally, server-side validation should also be implemented to double-check the data and ensure its integrity.

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $name = $_POST["name"];
    $email = $_POST["email"];

    // Client-side validation with JavaScript
    // Server-side validation
    if (empty($name)) {
        $errors[] = "Name is required";
    }

    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $errors[] = "Invalid email format";
    }

    if (empty($errors)) {
        // Process form data
    } else {
        // Display errors to the user
        foreach ($errors as $error) {
            echo $error . "<br>";
        }
    }
}
?>