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

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

    What Works For Me is :

    if ( !refreshed()) {
       //Your Submit Here
            if (isset( $_GET['refresh'])) {
                setcookie("refresh",$_GET['refresh'], time() + (86400 * 5), "/");
            }
    
        }    
    }
    
    
    function refreshed()
    {
        if (isset($_GET['refresh'])) {
            $token = $_GET['refresh'];
            if (isset($_COOKIE['refresh'])) {
                if ($_COOKIE['refresh'] != $token) {
                    return false;
                } else {
                    return true;
                }
            } else {
                return false;
            }
        } else {
            return false;
        }
    }  
    
    
    function createToken($length) {
        $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $charactersLength = strlen($characters);
        $randomString = '';
        for ($i = 0; $i < $length; $i++) {
            $randomString .= $characters[rand(0, $charactersLength - 1)];
        }
        return $randomString;
    }
    
    ?>
    

    And in your Form

     

提交回复
热议问题