Home  >  Article  >  Backend Development  >  How to use PHP to prevent repeated submission of forms

How to use PHP to prevent repeated submission of forms

php中世界最好的语言
php中世界最好的语言Original
2018-05-28 10:46:085432browse

This time I will show you how to use PHP to prevent repeated submission of forms, and what are the precautions for using PHP to prevent repeated submission of forms. The following is a practical case, let's take a look.

The code is very simple

I believe you are very smart and share a small demo with you, you can learn from it:

Specific code:

<?php
/*
* 2016年9月29日08:09:13
*/
session_start();
header("Content-Type: text/html;charset=utf-8");
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;web&#39;])){
  if(!valid_token()){
    echo "token error,请不要重复提交!";
  }else{
    echo &#39;成功提交,Value:&#39;.$_POST[&#39;web&#39;];
  }
}else{
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<title>PHP防止重复提交表单</title>
<meta name="keywords" content="PHP" />
<meta name="description" content="PHP防止重复提交表单" />
</head>
<body>
<p id="main">
  <p class="demo">
    <form method="post" action="">
      <input type="hidden" name="token" value="<?php echo $_SESSION[&#39;token&#39;]?>">
      <input type="text" class="input" name="web" value="脚本之家">
      <input type="submit" class="btn" value="提交" />
    </form>
  </p>
</p>
</body>
</html>
<?php }?>

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!

Recommended reading:

How to implement ADODB transaction processing in PHP

How to use thinkPHP to implement locking after three incorrect login passwords account

The above is the detailed content of How to use PHP to prevent repeated submission of forms. For more information, please follow other related articles on the PHP Chinese website!

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