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

后端 未结 23 1278
醉话见心
醉话见心 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

    You should really use a Post Redirect Get pattern for handling this but if you've somehow ended up in a position where PRG isn't viable (e.g. the form itself is in an include, preventing redirects) you can hash some of the request parameters to make a string based on the content and then check that you haven't sent it already.

    //create digest of the form submission:
    
        $messageIdent = md5($_POST['name'] . $_POST['email'] . $_POST['phone'] . $_POST['comment']);
    
    //and check it against the stored value:
    
        $sessionMessageIdent = isset($_SESSION['messageIdent'])?$_SESSION['messageIdent']:'';
    
        if($messageIdent!=$sessionMessageIdent){//if its different:          
            //save the session var:
                $_SESSION['messageIdent'] = $messageIdent;
            //and...
                do_your_thang();
        } else {
            //you've sent this already!
        }
    

提交回复
热议问题