Avoiding Form Resubmission Problems

The following information from Wikipedia explains the Form Resubmission Problems precisely.

When a web form is submitted to a server through an HTTP POST request, attempts to refresh the server response can cause the contents of the original POST to be resubmitted, possibly causing undesired results, such as a duplicate web purchase.

To avoid this problem, many web developers use the Post/Redirect/Get (PRG) pattern—instead of returning a web page directly, the POST returns a redirect. The HTTP 1.1 specification introduced the HTTP 303 (“See other”) response code to ensure that in this situation, browsers can safely refresh the server response without causing the initial POST request to be resubmitted.

The PRG pattern cannot address every scenario of duplicate form submission. For example, if a web user refreshes before the initial submission completes, possibly because of server lag, a duplicate POST occurs in certain user agents.

Diagram of a double POST problem encountered in user agents.
Source: Wikipedia | Diagram of a double POST problem encountered in user agents.
Diagram of the double POST problem above being solved by PRG.
Source: Wikipedia | Diagram of the double POST problem above being solved by PRG.

In Yii, we can solve this problem by calling refresh() or redirect() method instead of directly returning a view from the controller.

public function actionEntry()
    {
        $model = new EntryForm();

        if ($model->load(Yii::$app->request->post()) && $model->validate()) {
            // valid data received in $model

            // do something meaningful here about $model ...

            return $this->render('entry-confirm', ['model' => $model]);
        } else {
            // either the page is initially displayed or there is some validation error
            return $this->render('entry', ['model' => $model]);
    }

Code taken from Yii Framework Website.

Here as you can see, we have directly returned the view entry-confirm after a POST request. However, we know this isn’t the best practice. Instead, we could call refresh() or redirect() method which uses GET request.

Running low on budget? Get the best Shared hosting at an Affordable Rate!