How can PHP be used for server-side validation of form fields?

When submitting a form, it is crucial to validate the input data on the server-side to ensure data integrity and security. PHP can be used to validate form fields by checking for specific conditions such as empty fields, valid email addresses, or numeric values. By using PHP functions like isset(), empty(), and filter_var(), you can easily validate form fields before processing the data.

// Server-side validation of form fields using PHP

// Check if the form was submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    
    // Check if the name field is not empty
    if (empty($_POST["name"])) {
        $name_error = "Name is required";
    } else {
        $name = test_input($_POST["name"]);
    }
    
    // Check if the email field is not empty and is a valid email address
    if (empty($_POST["email"])) {
        $email_error = "Email is required";
    } else {
        $email = test_input($_POST["email"]);
        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $email_error = "Invalid email format";
        }
    }
    
    // Additional validation for other form fields
    
}

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