How to use token in PHP to prevent repeated submission of forms

墨辰丷
Release: 2023-03-29 16:36:01
Original
1464 people have browsed it

This article mainly introduces the method of PHP using token to prevent repeated submission of forms. It generates an encrypted random number and stores it in the token variable of the session, and at the same time puts the value into the form to hide the submission, so as to prevent repeated submission of the form. Function, friends who need it can refer to

<?php
/*
* PHP使用token防止表单重复提交
* 此处理方法纯粹是为了给初学者参考
*/
session_start();
function set_token() {
  $_SESSION[&#39;token&#39;] = md5(microtime(true));
}
function valid_token() {
  $return = $_REQUEST[&#39;token&#39;] === $_SESSION[&#39;token&#39;] ? true : false;
  set_token();
  return $return;
}
//如果token为空则生成一个token
if(!isset($_SESSION[&#39;token&#39;]) || $_SESSION[&#39;token&#39;]==&#39;&#39;) {
  set_token();
}
if(isset($_POST[&#39;test&#39;])){
  if(!valid_token()){
    echo "token error";
  }else{
    echo &#39;成功提交,Value:&#39;.$_POST[&#39;test&#39;];
  }
}
?>
<form method="post" action="">
  <input type="hidden" name="token" value="<?php echo $_SESSION[&#39;token&#39;]?>">
  <input type="text" name="test" value="Default">
  <input type="submit" value="提交" />
</form>
Copy after login

Summary: The above is the entire content of this article, I hope it can be helpful to everyone's study.

Related recommendations:

Detailed explanation of function examples for PHP to download files

PHP uses the header method to implement the file download function

PHP method to generate color QR code based on QRCODE

##

The above is the detailed content of How to use token in PHP to prevent repeated submission of forms. 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!