Search code examples
phpformssessionpost-redirect-get

POST/Redirect/GET with Error handling


The reason for this post is that I am trying to avoid the "form re submission error" that most browsers give off when a form is refreshed.

Take the following example:

The user is on a page called signpetition.php and shown a basic HTML form:

<div id="sign-errors" style="display: none;">
</div>

<form action="" method="post">
    <input type="submit" name="submit_button" value="sign petition" />
</form>

So, the user clicks the submit button and now the POST data will be read and verified.

signpetition.php

<?php
    if(isset($_POST['submit_button']))
    {
        // Do some validation

        if($errors == true)
        {
          // What to do here? I want to go back to the last page, but keep the errors. Should I store them in a session variable and then unset them after their use? I feel as though there must be a better solution to this.

            $_SESSION['error'] = "the error";
            header('Location: '. $_SERVER['REQUEST_URI'] , true, 303);
        exit;

        }
        else
        {
            $_SESSION['success'] = "your petition was successfully signed!";
            header('Location: '. $_SERVER['REQUEST_URI'] , true, 303);
        exit;
        }
    }
        ?>

So, to sum things up:

I want to avoid the form re submission issue, which is why I'm using the header redirection in my code


Solution

  • If the users are being redirected, then there should never be a form re-submission.

    Redirect them to submitted.php and use the following:

    if(isset($_SESSION['error'])){ echo'the error';}
    else if(isset($_SESSION['success'])){ echo'your petition was successfully signed!');}
    else{ echo 'unknown error.'; }