Where should conditional statements for form field validation be placed in a PHP script that handles form submissions?

Conditional statements for form field validation should be placed at the beginning of the PHP script that handles form submissions. This ensures that the validation logic is executed before any further processing of the form data takes place. By checking the submitted data against the desired criteria at the outset, you can prevent invalid or malicious input from being processed further.

<?php
// Check if form is submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Validate form fields
    if (empty($_POST["username"])) {
        $usernameErr = "Username is required";
    } else {
        $username = test_input($_POST["username"]);
        // Additional validation logic for username
    }

    if (empty($_POST["email"])) {
        $emailErr = "Email is required";
    } else {
        $email = test_input($_POST["email"]);
        // Additional validation logic for email
    }

    // Process valid form data
    if (empty($usernameErr) && empty($emailErr)) {
        // Further processing of form data
    }
}

// Function to sanitize form input
function test_input($data) {
    $data = trim($data);
    $data = stripslashes($data);
    $data = htmlspecialchars($data);
    return $data;
}
?>