double submission when refresh php

10,288

Solution 1

When you refresh the page - the POST IS SENT AGAIN

Some browsers actually warn you about that happening.

To prevent that I do:

if (isset($_POST['submitButton'])) { 
//do something

//..do all post stuff
header('Location: thisPage.php'); //clears POST
}


<form action = "table.php" method="post">
<label for="submitButton"></label>
<input type="submit" name="submitButton" id="submitButton"
value="Submit Form"/>
</form>

Solution 2

I use a session to keep from reposting.

session_start();

 if( isset($_SESSION['your_variable']) && 
     $_SESSION['your_variable'] == $_POST['your_variable'] ){
    // re-post, don't do anything. 
 }
 else{
    $_SESSION['your_variable'] = $_POST['your_variable'];
    // new post, go do something.
 } 

Solution 3

This is a standard behavior : when you reload the page, if it was posted, your browser replays the same request (with the POST).

To avoid this, you can use a redirection to the same page, with :

 <?php
 header("location:".$mycurrentURl);

This will reload the page, via a get request. This will prevent double posts.

Solution 4

I usually don't worry about this and just rely on the user NOT re-posting unless they want to. However, if you want to forbid it, you can use a nonce.

http://en.wikipedia.org/wiki/Cryptographic_nonce

Solution 5

when you refresh the page. browser post all the data again. so the same thing happens again to overcome this after doing something redirect the browser to same page again once like this

    if (isset($_POST['submitButton'])) { 
         //do something

         header("location:table.php");
    }
Share:
10,288

Related videos on Youtube

Aaron
Author by

Aaron

Updated on June 04, 2022

Comments

  • Aaron
    Aaron almost 2 years

    I'm trying to correct the issue of double submit in my script. When I press submit it only updates mysql once(which is what I want). However, when I hit refresh it updates mysql again. It seems to ignore the if statement once the refresh button is hit. What would I do to stop this

    here is my code

    if (isset($_POST['submitButton'])) { 
    //do something
     }
    
    
    <form action = "table.php" method="post">
    <label for="submitButton"></label>
    <input type="submit" name="submitButton" id="submitButton"
    value="Submit Form"/>
    </form>
    
  • edorian
    edorian over 12 years
    I'd rather use a csrf-token in the form than creating 2 request for a submit but i have to say it's a rather neat and easy to implement trick. Maybe die(); after the header(); ?