Prevent Double Form Submit using Tokens

前端 未结 7 1768
忘掉有多难
忘掉有多难 2020-12-10 07:44

I am trying to prevent the user from double submitting the forum by adding token hidden field.

So here is what I have done so far (before the forum loads I have this

7条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-10 08:40

    For the same issue I made a code to use it for my own stuff. It has the PRG pattern and flexible to use it on same page or with extern PHP file for redirection - Easy to use and safe, maybe this might help you.

    class unPOSTer {
    
            private 
                $post = "KEEP_POST";
    
            public function __construct(string $name = null) {
                if (version_compare(PHP_VERSION, "5.4.0") >= 0) {
                    if (session_status() == PHP_SESSION_NONE) {
                        session_start();
                    }
                } else {
                    if (!$_SESSION) {
                        session_start();
                    }
                }
                $this->post = $name;
            }
    
            public function unPost() {
                if (session_status() !== PHP_SESSION_ACTIVE) {
                    session_start();
                } elseif (strcasecmp($_SERVER["REQUEST_METHOD"],"POST") === 0) {
                    $_SESSION[$this->post] = $_POST;
                    header("Location: " . $_SERVER["PHP_SELF"] . "?" . $_SERVER["QUERY_STRING"]);
                    exit;
                } elseif (isset($_SESSION[$this->post])) {
                    $_POST = $_SESSION[$this->post];
                }
            }
    
            public function retrieve($data) {
                if (isset($_SESSION[$this->post])) {
                    $posts = @$_SESSION[$this->post][$data];
                    if (isset($posts)) {
                        return $posts;
                    } else {
                        return null;
                    }
                } 
            }
    
            public function reset() {
                if (isset($_SESSION[$this->post])) {
                    unset($_SESSION[$this->post]);
                }
            }
        }
    

    Then use it like this:

    unPost();
    ?>
    
    " placeholder="First Name"> " placeholder="Last Name">
    reset(); ?>

    Not much to configure, do it on every page you send form data if you like. The retrieve() method spits out the data you have sent, in case if you might go back and fix something. Feel free to fork/pull it at my GitHub page I added 2 demos there.

提交回复
热议问题