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

伊谢尔伦
Release: 2023-03-02 18:04:01
Original
2074 people have browsed it

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;
Copy after login

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"/>
Copy after login

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();
}
Copy after login


Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template