What are best practices for handling form submissions in PHP, particularly when validating user input for registration forms?

When handling form submissions in PHP, it is important to validate user input to ensure data integrity and security. One of the best practices is to use server-side validation to check for required fields, data formats, and any constraints before processing the form data. This helps prevent malicious input and improves the overall user experience by providing immediate feedback on errors.

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Validate form fields
    $errors = [];

    // Check if required fields are not empty
    if (empty($_POST['username'])) {
        $errors[] = "Username is required.";
    }

    if (empty($_POST['email'])) {
        $errors[] = "Email is required.";
    }

    // Validate email format
    if (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
        $errors[] = "Invalid email format.";
    }

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