Table of Contents
回复内容:
Home Backend Development PHP Tutorial 如何防止 POST 数据重复提交!

如何防止 POST 数据重复提交!

Jun 06, 2016 pm 08:31 PM
html mysql php

如题,在不使用验证码的情况下!

回复内容:

如题,在不使用验证码的情况下!

所有“通过前台JS,约束提交行为本身不会重复发生”的答案都是彻底错误的。

弱网络时如果POST请求到达了服务器响应却没回去,此时客户端报浏览器原生的超时错误,访客按F5重发,你的JS如之奈何?!

JS阻止重复点击按钮,仅仅是“锦上添花”的体验改进而已,根本称不上“防重复提交”的可靠方案。事实上我们也根本做不到“防止用户重复提交”——HTTP请求的到达能拦的了吗?这个需求的本质是:如何让重复提交的内容能够被识别出来(从而不被重复处理)

重复提交的鉴别,无非两种思路:

  1. 比对内容相同的提交是否重复出现。
  2. 为每次提交标号,比对相同编号的提交是否重复出现。

而其中(1)又是等同于(2)的。因为提交不可能全量比较,只可能计算一个哈希值(MD5等)去比,这样无非就是依赖提交的内容做了一个标号。

HTTP协议是无状态的,不能从HTTP协议本身下手,所以自然要在业务层加上这个标号。

考虑清楚前提,办法就容易了。用种种手段把表单标上号就可以。不限于以下方法:

  • 服务器下发表单时,在表单里附加一个毫秒时间戳或唯一ID
  • 客户端JS在表单内,插入点按提交按钮的时间戳,以及浏览器的信息
  • 服务器端收到表单时,对表单的内容做哈希签名并缓存
  • 有些业务逻辑天生就是防重复的。例如订单的状态流转,一般都是单向、不重复且不可逆的。此时要充分利用业务逻辑,尽量在直接回弹不合法请求的同时,就把重复提交顺手一起干掉。

后端生成token,保存数据前验证

楼上说得都很好了,补充下,除了使用token进行校验外,还可以使用POST-Redirect-GET(PRG)的方式——最后呈现给用户的是一个GET的页面,即使用户按F5刷新页面也不会导致重复提交表单。

参考一下:表单令牌

PHP生成表单时设置一个token隐藏域,提交后JS则可以辅助把提交按钮设为不可点击.
提交表单时进行验证,相同则写入数据库并生成新的token.
token生成算法,比如:

<code>$token = sha1(uniqid(mt_rand(), true));
</code>
Copy after login

uniqid获取一个带前缀(mt_rand),末尾带熵(true),基于当前时间微秒数的唯一编号.mt_rand用于生成更好的随机数.

作为一名Python程序猿,使用Django框架时,直接在模板里面,在

里面直接加上{% csrf_token %}

在第一次提交之后设置一定时间才能提交第二次,javascript里面有一个叫做debounce的可以应用到你得场景,
你可以把你提交的动作放到debounce里面,例如:

<code>'use strict';

var debounce = function(func, timeout) {

    var timer;

    return function() {
        var _this = this;
        var args = Array.prototype.slice.call(arguments);
        clearTimeout(timer);
        timer = setTimeout(function() {
            func.apply(_this, args);
        }, timeout);
    };
};

</code>
Copy after login

这样当你再调用post的提交方法submit()的时候,

<code>var debounced = debounce(submit, 100);

debounced();
debounced();
debounced();
debounced();
</code>
Copy after login

它只会提交一次。

1、header地址重定向
2、JS跳转其他页面
3、设置Token并验证

做一个令牌吧,当正在处理数据时,令牌为false,不能提交;当无数据处理时,令牌为true,提交处理数据。

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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)

The Future of PHP: Adaptations and Innovations The Future of PHP: Adaptations and Innovations Apr 11, 2025 am 12:01 AM

The future of PHP will be achieved by adapting to new technology trends and introducing innovative features: 1) Adapting to cloud computing, containerization and microservice architectures, supporting Docker and Kubernetes; 2) introducing JIT compilers and enumeration types to improve performance and data processing efficiency; 3) Continuously optimize performance and promote best practices.

How to open phpmyadmin How to open phpmyadmin Apr 10, 2025 pm 10:51 PM

You can open phpMyAdmin through the following steps: 1. Log in to the website control panel; 2. Find and click the phpMyAdmin icon; 3. Enter MySQL credentials; 4. Click "Login".

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

Understanding HTML, CSS, and JavaScript: A Beginner's Guide Understanding HTML, CSS, and JavaScript: A Beginner's Guide Apr 12, 2025 am 12:02 AM

WebdevelopmentreliesonHTML,CSS,andJavaScript:1)HTMLstructurescontent,2)CSSstylesit,and3)JavaScriptaddsinteractivity,formingthebasisofmodernwebexperiences.

The Role of HTML: Structuring Web Content The Role of HTML: Structuring Web Content Apr 11, 2025 am 12:12 AM

The role of HTML is to define the structure and content of a web page through tags and attributes. 1. HTML organizes content through tags such as , making it easy to read and understand. 2. Use semantic tags such as, etc. to enhance accessibility and SEO. 3. Optimizing HTML code can improve web page loading speed and user experience.

How to use single threaded redis How to use single threaded redis Apr 10, 2025 pm 07:12 PM

Redis uses a single threaded architecture to provide high performance, simplicity, and consistency. It utilizes I/O multiplexing, event loops, non-blocking I/O, and shared memory to improve concurrency, but with limitations of concurrency limitations, single point of failure, and unsuitable for write-intensive workloads.

PHP: Is It Dying or Simply Adapting? PHP: Is It Dying or Simply Adapting? Apr 11, 2025 am 12:13 AM

PHP is not dying, but constantly adapting and evolving. 1) PHP has undergone multiple version iterations since 1994 to adapt to new technology trends. 2) It is currently widely used in e-commerce, content management systems and other fields. 3) PHP8 introduces JIT compiler and other functions to improve performance and modernization. 4) Use OPcache and follow PSR-12 standards to optimize performance and code quality.

MySQL: An Introduction to the World's Most Popular Database MySQL: An Introduction to the World's Most Popular Database Apr 12, 2025 am 12:18 AM

MySQL is an open source relational database management system, mainly used to store and retrieve data quickly and reliably. Its working principle includes client requests, query resolution, execution of queries and return results. Examples of usage include creating tables, inserting and querying data, and advanced features such as JOIN operations. Common errors involve SQL syntax, data types, and permissions, and optimization suggestions include the use of indexes, optimized queries, and partitioning of tables.

See all articles