Home >Backend Development >PHP Tutorial >How to add Token verification mechanism in PHP form
In web development, forms are an important channel for communication between users and servers. To ensure security, we need to add a Token verification mechanism when submitting the form to avoid attacks by malicious attackers.
The basic principle of Token verification is: the server generates a random number, passes the Token to the client by adding a hidden field in the form, the client sends the Token back to the server when submitting the form, and the server verifies the correctness of the Token. , if there is a match, allow form submission, otherwise deny submission.
Below we will introduce how to implement the Token verification mechanism in PHP.
We can use PHP's rand() function to generate a random number as a Token, and then add the Token to the hidden field in the form, The code is as follows:
<?php $token = rand(); //生成随机数作为Token ?> <form action="submit.php" method="post"> <input type="hidden" name="token" value="<?php echo $token; ?>"> <!-- 其他表单元素 --> <button type="submit">提交</button> </form>
After the form is submitted, we need to verify whether the Token in the form is correct. We can store the Token in the server's session and compare the Token submitted by the form with the Token stored in the session. The code is as follows:
<?php session_start(); // 开启session $token = $_POST['token']; //获取表单提交的Token值 if ($token === $_SESSION['token']) { //判断Token是否匹配 // ... 其他操作 } else { echo 'Token验证失败'; } ?>
Note: After each form submission and verification is successful, we need Regenerate a new Token and update the Token value stored in the session. This avoids repeated form submissions and malicious attacks.
<?php session_start(); // 开启session // 验证Token if ($_POST['token'] !== $_SESSION['token']) { die('Token验证失败'); } // 更新Token $_SESSION['token'] = rand(); // ... 其他操作 ?>
In this way, we successfully added the Token verification mechanism to the PHP form and improved the security of the website.
The above is the detailed content of How to add Token verification mechanism in PHP form. For more information, please follow other related articles on the PHP Chinese website!