What are best practices for error handling and validation in PHP forms, especially when using a step-by-step form process like an "Affenformular"?

When working with step-by-step form processes like an "Affenformular," it's important to implement error handling and validation to ensure that the user inputs are correct before proceeding to the next step. One best practice is to perform validation on each step of the form and display error messages if any input is invalid. Additionally, it's crucial to sanitize user inputs to prevent any malicious code injection.

// Validate and sanitize user inputs for each step of the form

// Step 1: Validate and sanitize input
if(isset($_POST['step1_submit'])){
    $name = isset($_POST['name']) ? htmlspecialchars(trim($_POST['name'])) : '';
    
    // Validate name input
    if(empty($name)){
        $errors[] = "Name is required.";
    }

    // Proceed to next step if no errors
    if(empty($errors)){
        // Process step 1 data
    }
}

// Step 2: Validate and sanitize input
if(isset($_POST['step2_submit'])){
    $email = isset($_POST['email']) ? filter_var(trim($_POST['email']), FILTER_SANITIZE_EMAIL) : '';
    
    // Validate email input
    if(!filter_var($email, FILTER_VALIDATE_EMAIL)){
        $errors[] = "Invalid email address.";
    }

    // Proceed to next step if no errors
    if(empty($errors)){
        // Process step 2 data
    }
}

// Display error messages
if(!empty($errors)){
    foreach($errors as $error){
        echo "<p>$error</p>";
    }
}