What are common methods for validating user input in multi-page PHP forms to prevent errors?

Validating user input in multi-page PHP forms is crucial to prevent errors and ensure data integrity. Common methods include using PHP functions like `filter_var()` for basic validation, regular expressions for more complex validation, and session variables to store and pass data between form pages. Additionally, implementing client-side validation using JavaScript can provide immediate feedback to users before submitting the form.

// Example of validating user input in a multi-page PHP form

// Check if form data has been submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Validate input from the first form page
    $email = $_POST['email'];
    
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $errors[] = "Invalid email format";
    }
    
    // Store validated data in session variables
    session_start();
    $_SESSION['email'] = $email;
    
    // Redirect to the next form page
    header("Location: form_page2.php");
    exit();
}

// In the next form page, retrieve and validate the stored data
session_start();

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Validate input from the second form page
    $password = $_POST['password'];
    
    if (strlen($password) < 8) {
        $errors[] = "Password must be at least 8 characters long";
    }
    
    // Continue validating other form fields
    
    if (empty($errors)) {
        // Process the form data
        $email = $_SESSION['email'];
        // Process the rest of the form data
    }
}