Prevent Form resubmission upon hitting back button

前端 未结 8 1992
无人及你
无人及你 2020-12-03 05:17

I have searched many posts here and elsewhere but can\'t seem to find a solution to my problem. I have a page which displays database entries: database.php. These entries c

相关标签:
8条回答
  • 2020-12-03 05:28

    You need to remove the request which POST data from browser history

    history.replaceState("", "", "/the/result/page")
    

    See this answer

    Also you may follow the Post/Redirect/Get pattern.

    0 讨论(0)
  • 2020-12-03 05:29
    header("Cache-Control: no cache");
    
    session_cache_limiter("private_no_expire");
    

    NOTE: After using the post data what you have submitted from the form then, these two lines should be used at the end of function.so, when we are back to the redirected page, it will not ask you to resubmit the page. This will work.

    0 讨论(0)
  • 2020-12-03 05:30

    The solution the works for me is

    $(document).ready( function() {
    //prevent form submit on refresh or resubmit with back button
    if ( window.history.replaceState ) window.history.replaceState( null, null, window.location.href );
    }
    
    0 讨论(0)
  • 2020-12-03 05:38

    I used the answer at How do I detect if a user has got to a page using the back button? to detect whether or not the visit was triggered by a browser's back button click, and then if that was the case, I used JavaScript to reload the page. When the page is reloaded, my code already handles the corresponding validations to make sure that the form is never submitted twice. The important part in my case was forcing the page reload when the form was revisited after clicking the browser's back button. This is my code in the URL where I wanted to apply this validation:

    <script type="text/javascript">
        if (window.performance && window.performance.navigation.type == window.performance.navigation.TYPE_BACK_FORWARD) {
            location.reload();
        }
    </script>
    
    0 讨论(0)
  • 2020-12-03 05:41

    I know this question is old, but having this issue myself, two lines I've discovered that works are:

    header("Cache-Control: no cache");
    session_cache_limiter("private_no_expire");
    
    0 讨论(0)
  • 2020-12-03 05:45

    An alternative solution that also works if/when the page is reloaded involves checking the post's originality using $_SESSION. In a nutshell, check for a unique or random string.

    In the form, add an input element with a value set using rand() or microtime():

    <input type="hidden" name="formToken" value="<?php echo microtime();?>"/>
    

    And then wrap the PHP function to validate and parse the form data in an if block:

    if(!isset($_SESSION['formToken']) || $_POST['formToken'] !== $_SESSION['formToken'])){
           $_SESSION['formToken'] = $_POST['formToken'];
          /*continue form processing */
    }
    
    0 讨论(0)
提交回复
热议问题