Skip to content
PHP Logo

How can errors in form submission be handled in PHP without relying on JavaScript for redirection?

When handling form submissions in PHP, errors can be displayed on the same page by checking for validation errors and storing them in an array. If there are errors, the form can be displayed again with the errors listed next to the respective fields. This can be achieved without relying on JavaScript for redirection by using PHP's header function to redirect to the same page after form submission.

php
<?php
$errors = array();

// Check for form submission
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Validate form data
    if (empty($_POST["name"])) {
        $errors[] = "Name is required";
    }

    // If there are errors, display form with errors
    if (!empty($errors)) {
        foreach ($errors as $error) {
            echo $error . "<br>";
        }
    } else {
        // Process form data
        // Redirect to the same page after form submission
        header("Location: " . $_SERVER['PHP_SELF']);
        exit();
    }
}
?>

<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
    <input type="text" name="name" placeholder="Name">
    <!-- Add more form fields here -->
    <button type="submit">Submit</button>
</form>