Вопрос

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

Это было полезно?

Решение

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.'; }

Другие советы

I know this is old, but I wanted to add that there is nothing wrong with your original solution regarding storing a message in the SESSION object for a single use. This is a common practice known as "Flash Messages", which are messages stored in the session that are deleted when read a single time. The technique was made popular by Rails. A PHP summary is below:

http://www.phpdevtips.com/2013/05/simple-session-based-flash-messages/

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top