How can PHP be used to ensure that users do not reach the thank you page unless all form data is correctly entered?

To ensure that users do not reach the thank you page unless all form data is correctly entered, we can use PHP to validate the form data before allowing the user to proceed. This can be done by checking if all required form fields are filled out and if they meet certain criteria (such as being a valid email address or phone number). If the form data is not valid, we can display error messages and prevent the user from accessing the thank you page.

<?php
// Check if form is submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Check if all required fields are filled out
    if (isset($_POST['name']) && isset($_POST['email']) && isset($_POST['message'])) {
        // Check if email is valid
        if (filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
            // Process form data and redirect to thank you page
            header("Location: thank-you-page.php");
            exit();
        } else {
            echo "Invalid email address.";
        }
    } else {
        echo "Please fill out all required fields.";
    }
}
?>