Home > Backend Development > PHP Tutorial > How to add Token verification mechanism in PHP form

How to add Token verification mechanism in PHP form

王林
Release: 2023-06-24 18:08:01
Original
1099 people have browsed it

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.

  1. Add a hidden field in the form

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>
Copy after login
  1. Verify Token

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验证失败';
}
?>
Copy after login

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();
// ... 其他操作
?>
Copy after login

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!

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