Home  >  Article  >  Backend Development  >  Introduction to how to prevent repeated submission of forms in PHP (code example)

Introduction to how to prevent repeated submission of forms in PHP (code example)

不言
不言forward
2019-02-11 09:21:122493browse

What this article brings to you is an introduction to the method of preventing repeated submission of forms in PHP (code examples). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

I am ashamed to say that I made a low-level mistake when I was working on a project a few days ago. When submitting forms in the company's backend, one was used by my own employees, and the other was written by myself in html. The form was submitted repeatedly without verification, and the result was an error. Write it down and record it to remind yourself and never neglect it.

Solution

In fact, there are many methods. I only give a few simple examples.

Framework

Many frameworks have the function of preventing repeated submissions. Everyone should know about it, so I won’t go into details here.

Front end

The principle is very simple. After the user clicks submit, just use JS to gray out the submit button.

Backend

That is, PHP is used for verification. Of course, it is not limited to the following types

Cookie

The user submits the form to the backend, in the Cookie Make a mark, and repeated submissions within the specified time will be invalid. But this method will fail if the user disables cookies.

<?php

if (isset($_COOKIE['formFlag'])) {
    exit('error');
}

// 处理数据

// 30秒内重复提交无效
setcookie('formFlag', time(), time() + 30);

Session

When displaying the form page, a random number is generated and stored in the Session and the hidden field of the form. When submitting for the first time, compare and successfully delete the value in the Session.

<?php

if (!isset($_SESSION['formFlag']) || $_POST['formFlag'] != $_SESSION['formFlag']) {
    exit('error');
}

// 处理数据

unset($_SESSION['formFlag']);

The above is the detailed content of Introduction to how to prevent repeated submission of forms in PHP (code example). For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete