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:172081browse

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:

<input type="hidden" value="<?php echo $_token;?>" name="_token"/>

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