What are the best practices for handling validation errors in PHP when processing form data?

When handling validation errors in PHP when processing form data, it is important to properly sanitize and validate user input to prevent security vulnerabilities and ensure data integrity. Using PHP functions like filter_var() or regular expressions can help validate input fields such as email addresses, phone numbers, or passwords. Additionally, displaying clear error messages to the user can help them correct their input easily.

// Example of handling validation errors in PHP when processing form data

// Check if form is submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Validate email input
    $email = $_POST['email'];
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $errors[] = "Invalid email format";
    }

    // Validate password input
    $password = $_POST['password'];
    if (strlen($password) < 8) {
        $errors[] = "Password must be at least 8 characters long";
    }

    // Display errors or process form data
    if (!empty($errors)) {
        foreach ($errors as $error) {
            echo $error . "<br>";
        }
    } else {
        // Process form data
        // Insert data into database, send email, etc.
    }
}