Home Backend Development PHP Tutorial PHP生成token防止表单重复提交

PHP生成token防止表单重复提交

Jun 23, 2016 pm 01:25 PM

1、提交按钮置disabled

当用户提交后,立即把按钮置为不可用状态。这种用js来实现。

提交前代码如下:


$("#submit").attr('disabled','true');

$("#submit").val("正在提交,请稍等");

执行后,把按钮置为原来状态

代码如下:


$('#submit ').removeAttr('disabled');

$("#submit ").val("确定提交");

这样只是针对一些简单的前台提交了,如果我们自己做个表单站长提交给我们php逻辑层文件就过滤这那个js了。

过期时间法

用户提交按钮后生成一个token(每次业务提交token 为唯一值)存入session,并设置过期时间。当用户再此提交时,检测token是否一致且是否过期,若一致且没有过期,则认为提交了二次

例子


/*

* PHP简单利用token防止表单重复提交

* 此处理方法纯粹是为了给初学者参考

*/

session_start();

function set_token() {

$_SESSION['token'] = md5(microtime(true));

}

function valid_token() {

  $return = $_REQUEST['token'] === $_SESSION['token'] ? true : false;

  set_token();

  return $return;

}

//如果token为空则生成一个token

if(!isset($_SESSION['token']) || $_SESSION['token']=='') {

  set_token();

}

if(isset($_POST['test'])){

if(!valid_token()){

  echo "token error";

  }else{

  echo '成功提交,Value:'.$_POST['test'];

  }

}

?>

 

 

 

方法二


//开启session

session_start();

//如果有提交标识

if(isset($_GET['action']) && $_GET['action'] === 'save'){

  //如果有session且跟传过来的值一样才算提交

  if(isset($_SESSION['__open_auth']) && isset($_POST['auth']) && $_SESSION['__open_auth'] == $_POST['auth']){

  print_r($_POST);

  $_SESSION['__open_auth'] = null;//清空

  } else {

  //走起

  header("location: post.php");

  }

  exit();

}

//授权

$auth = $_SESSION['__open_auth'] = time();

?>

 

 

post

 

 

       

  •    

       

       

  •    

  •    

       

  •    

  •    

       

  •    

  •    

       

  •  

 

mysql php数据库重复记录防止


$link=mysql_connect(‘localhost’,’root’,’root’); //得到MySQL数据库连接 

$username=$_GET["name"]; //得到从客户端表单传过来的数据 

$q="select * from usertable where user_name='$username'"; 

mysql_query("SET NAMES gb2312"); //避免出现中文乱码 

$rs = mysql_query($q, $link); //查询数据库 

$num_rows = mysql_num_rows($rs); //得到查询结果的总行数 

if($num_rows==0) 

$exec="insert into student (user_name) values ($username)"; 

mysql_query("SET NAMES gb2312"); 

mysql_query($exec, $link); //若没有此用户则将数据插入到数据库(注册用户) 

echo "用户注册成功!"; 

else 

echo "该用户名已存在,请重新选择用户名!"; 

?>

session过期法有非常重要的一点是一个session设置与提交成功与不成功时的一个session验证了,这个有点像登录一样的如果登录成功了我们要清除session这个原理也差不多。

<br />
Copy after login


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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

Explain the concept of late static binding in PHP. Explain the concept of late static binding in PHP. Mar 21, 2025 pm 01:33 PM

Article discusses late static binding (LSB) in PHP, introduced in PHP 5.3, allowing runtime resolution of static method calls for more flexible inheritance.Main issue: LSB vs. traditional polymorphism; LSB's practical applications and potential perfo

How does session hijacking work and how can you mitigate it in PHP? How does session hijacking work and how can you mitigate it in PHP? Apr 06, 2025 am 12:02 AM

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

Describe the SOLID principles and how they apply to PHP development. Describe the SOLID principles and how they apply to PHP development. Apr 03, 2025 am 12:04 AM

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

How to automatically set permissions of unixsocket after system restart? How to automatically set permissions of unixsocket after system restart? Mar 31, 2025 pm 11:54 PM

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

How to debug CLI mode in PHPStorm? How to debug CLI mode in PHPStorm? Apr 01, 2025 pm 02:57 PM

How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

See all articles