tags:

views:

122

answers:

3

For example, I ask this question and click "Post your question" and stay in the current page. Now I may click the "refresh" button of my browser to see new answers. But I find that on my website, if I click the "refresh" button, a duplicated question will be published. How to avoid this problem? I am using PHP.

A: 

First of all, use POST for your form. Pretty much every browser will ask the user to confirm when refreshing a POSTed form result, since it has to resubmit it.

Second, in your form processing script, check to see if the question already exists - or set a session for the user and keep track of if they've recently submitted something.

Amber
But my browser(Firefox) doesn't ask me to confirm.
Steven
Then your browser has a bug. It works for me.
Chacha102
+5  A: 

It is common practice after a POST request, to redirect to the same page to avoid this problem.

Lets say you are on /ask_question.php

Your opening <form> tag might look like this:

<form action="/ask_question.php" method="post">

Now, in your /ask_question.php do something like this:

if( isset($_POST['new-question'])){
    // Do your processing here

    // On success:
    header('Location: /ask_question.php');
    exit(); // End the request
}

Update It is important to only redirect after a valid $_POST request has been handled. I test for a form field named new-question but you should use any form field name that has to be present for the $_POST to succeed

This processes their posted data, then on success, redirects back to the same page. The only difference now, is that when they click refresh, no information will be posted.

Note Just make sure nothing is echo'ed out prior to the header call.

Doug Neiner
Beat me to it. =)
Alix Axel
@Alix haha. However, I got too verbose. Your answer is much shorter and probably communicates the answer better :)
Doug Neiner
@Doug: Verbosity is good. =)
Alix Axel
What does if( isset($_POST['new-question'])) mean? Does it make a difference?
Steven
I updated my answer to further explain that point, but it was my way of showing a test for a valid $_POST request. You can do whatever you want, but just make sure the redirect will only happen after a `$_POST` request, otherwise you will create an endless loop of redirects.
Doug Neiner
Do you mean if a user clicks the "refresh" of his web browser,( isset($_POST['new-question'])) will return false?
Steven
Steven, if you follow my code exactly, the user will be "redirected" back to the page. If they then click `refresh` there is no POST data floating around to be submitted again. The request will be a `GET` request and no `POST` data will be sent at all so the `isset` test would return `false`
Doug Neiner
+1  A: 

Submit the form using POST, upon submission validate and if everything is fine redirect the user to a success page, that way if the user refreshes the page all he'll do is see the "thank you" page again.

Alix Axel