How to prevent form resubmission when page is refreshed (F5 / CTRL+R)

后端 未结 23 1591
醉话见心
醉话见心 2020-11-22 00:46

I have a simple form that submits text to my SQL table. The problem is that after the user submits the text, they can refresh the page and the data gets submitted again with

23条回答
  •  野的像风
    2020-11-22 01:42

    Using the Post/Redirect/Get pattern from Keverw answer is a good idea. However, you are not able to stay on your page (and I think this was what you were asking for?) In addition, it may sometimes fail:

    If a web user refreshes before the initial submission has completed because of server lag, resulting in a duplicate HTTP POST request in certain user agents.

    Another option would be to store in a session if text should be written to your SQL database like this:

    if($_SERVER['REQUEST_METHOD'] != 'POST')
    {
      $_SESSION['writeSQL'] = true;
    }
    else
    {
      if(isset($_SESSION['writeSQL']) && $_SESSION['writeSQL'])
      {
        $_SESSION['writeSQL'] = false;
    
        /* save $_POST values into SQL */
      }
    }
    

提交回复
热议问题