开发者

How to avoid duplicate when a user click the "refresh" button of his browser?

开发者 https://www.devze.com 2022-12-15 07:36 出处:网络
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,

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 p开发者_如何学Goublished. How to avoid this problem? I am using PHP.


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.


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消