What are the best practices for handling errors in PHP registration forms?

When handling errors in PHP registration forms, it is important to validate user input, provide clear error messages, and prevent SQL injection attacks. One way to handle errors is to check for empty fields, validate email addresses, and ensure that passwords meet certain criteria before processing the form.

// Check if form is submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    
    // Validate input fields
    if (empty($_POST["username"]) || empty($_POST["email"]) || empty($_POST["password"])) {
        $error = "All fields are required";
    } else {
        // Validate email address
        if (!filter_var($_POST["email"], FILTER_VALIDATE_EMAIL)) {
            $error = "Invalid email format";
        }
        
        // Validate password criteria
        if (strlen($_POST["password"]) < 8) {
            $error = "Password must be at least 8 characters long";
        }
        
        // If no errors, process form
        if (!isset($error)) {
            // Process registration logic here
        }
    }
}