Home  >  Article  >  Backend Development  >  Use Session token in php to prevent repeated submission of Ajax forms

Use Session token in php to prevent repeated submission of Ajax forms

伊谢尔伦
伊谢尔伦Original
2016-12-01 11:30:171977browse

There are two main ways to prevent repeated submission of forms:

1) Through redirection (non-Ajax form submission)

2) Through Session Token (Session token)

When the client requests the page, the server will generate a random number, and place the random number into the session, and then send the random number to the client; if the client submits for the first time, the random number will be sent to the server, and the server will receive the random number and communicate with the session Compare with the random number saved in the server. At this time, the two values ​​are the same. The server considers it to be the first submission and will update the random value on the server side; if it is submitted again at this time, the client sends a random number to the server. The random number is still the same as before, but the random number on the server side has changed. If the two are different, the server considers this to be a repeated submission.

Generate a random number and encrypt it using md5:

$_token = md5(microtime()+rand(1,10000));
$_SESSION['_token'] = $_token;

Send the value to the client and submit it as a hidden field in the form:

Then compare the submitted data with the data in the server Session when submitting , if it is empty or unequal, it is considered an illegal operation:

if(!isset($_POST('_token'))){
    echo json_encode(array('status'=>'failed','msg'=>'非法操作!'));
    exit();
}
if(isset($_POST['_token']) && $_POST['_token']!=$_SESSION['_token']){
    echo json_encode(array('status'=>'failed','msg'=>'表单只能提交一次,不能重复提交!'));
    exit();
}


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn