So how do you avoid duplicate submission form this phenomenon happen? We can see from many aspects, first from the front end to make restrictions. In the front-end javascript is disabled after a button is clicked, the disabled, this simple method of preventing multiple clicks the submit button, but the disadvantage is that if the user has disabled javascript script is invalid. Second, we can do after submitting the redirect page redirection, that is submitted after the jump to a new page, the main F5 avoid duplicate submissions, but there are drawbacks. Thirdly, it is made unique database index constraint. Fourth, it is to do the session token authentication.
We now come to study the simple use of token session to prevent the form of repeated submission method.
We in the form with an input hidden field, type = "hidden", its value is value used to hold the token value. When a page refresh the token value will change, after the submission of the judgment the token value is correct, if submitted to the front of the token and the background do not match is considered is repeated submission.
<?php
/*
* prevent form submiting repeatly
*/
session_start();
header("Content-Type: text/html;charset=utf-8");
function set_token() {
$_SESSION['token'] = md5(microtime(true));
}
function valid_token() {
$return = $_REQUEST['token'] === $_SESSION['token'] ? true : false;
set_token();
return $return;
}
//if token is null, gen a new token
if(!isset($_SESSION['token']) || $_SESSION['token']=='') {
set_token();
}
if(isset($_POST['web'])){
if(!valid_token()){
echo "token error, repeating submit!";
}else{
echo 'Submit success, Value:'.$_POST['web'];
}
}else{
?>
<form method="post" action="">
<input type="hidden" name="token" value="<?php echo $_SESSION['token']?>">
<input type="text" class="input" name="web" value="www.goocode.net">
<input type="submit" class="btn" value="Submit" />
</form>
<?php
}
?>
Above is a simple example of a simple form to prevent duplication, for reference only. So the actual project development, the form token to do more complex processing, that we say token verification. Likely to do: verify the source domain, namely the antecedents, whether external submit; matching the action to be performed is to add, modify or delete; the next most important is building a token, the token can be using reversible encryption algorithm, as far as possible complex, because the plaintext or unsafe. Token verification of the specific algorithm can refer to the major PHP framework, such as ThinkPHP provides a good token authentication function.