What are the best practices for handling form validation errors in PHP without unnecessary redirection?

When handling form validation errors in PHP without unnecessary redirection, it is best to display the error messages on the same page as the form. This can be achieved by storing the error messages in an array and checking for any errors before processing the form submission. By displaying the errors inline with the form, users can easily see what needs to be corrected without being redirected to a different page.

<?php
$errors = [];

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Perform form validation
    if (empty($_POST["username"])) {
        $errors[] = "Username is required";
    }

    // Check for other form fields and validation rules

    // If there are no errors, process the form submission
    if (empty($errors)) {
        // Process form data
    }
}

// Display form and error messages
?>

<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
    <input type="text" name="username" placeholder="Username">
    <!-- Add other form fields -->

    <?php if (!empty($errors)) : ?>
        <div class="error">
            <ul>
                <?php foreach ($errors as $error) : ?>
                    <li><?php echo $error; ?></li>
                <?php endforeach; ?>
            </ul>
        </div>
    <?php endif; ?>

    <button type="submit">Submit</button>
</form>