


Really solve the problem of repeated form submission php code_PHP tutorial
I have seen many js or jquery programs to prevent repeated submission of forms, but this is just a simple method. If we do not submit the form from this page and directly find the page that accepts data, this js processing method will be invalid. , below I use some methods in php to solve it.
Previously used js form method to prevent repeated submission
The code is as follows | Copy code | ||||
//The following three methods are called respectively
|
The code is as follows | Copy code |
Method="post">
|
The code is as follows | Copy code |
http://localhost/mytest/token/form.php?data=test&submit=%E6%8F%90%E4%BA%A4 |
The post cannot be seen in the address bar. You can see the following information using fiebug
You can simply think that get transmits data explicitly, while post transmits data implicitly, but another big difference is that post supports more and larger data transmission.
Next, when the form code is written, let us write the server script (here is PHP). Very simple ~
代码如下 | 复制代码 |
if ( isset( $_POST['submit'] ) ) { //表单提交处理 $data = isset( $_POST['data'] ) ? htmlspecialchars( $_POST['data'] ) : ''; //Insert or Update数据库 $sql = "insert into test (`string`) values ('$data')"; //do query echo $sql; } ?> |
Because data is transmitted by post here, you can use PHP's $_POST global variable to obtain the data submitted by the form. All form data submitted to the server using the post method will be saved in this $_POST global variable. You might as well try the print_r($_POST) variable and you will understand.
First check whether submit exists in the $_POST array. If it exists, it proves that the form was submitted. Just like there seems to be something called ispostback in asp.net, but this is not so rigorous, but it doesn’t matter and will be solved later. of this question.
After receiving the data in the input box, it is $_POST['data']. Don't forget to use htmlspecialchars to perform html filtering on this to prevent problems caused by inputting html tags or javascript (seems to be called an XSS vulnerability). Finally, it is spliced into the sql statement and sent to the database for running (it is just that paperen does not use some functions for operating the database in detail here, such as mysql_query, so I am interested in completing it myself). Congratulations, you have successfully completed a data entry function here, but there is something you must improve. After inserting data, you must give the operator a prompt~~ At least prompt me whether the operation failed or succeeded. So the entire code paperen is written as follows.
The code is as follows | Copy code | ||||
//Form submission processing $data = isset( $_POST['data'] ) ? htmlspecialchars( $_POST['data'] ) : ''; //connect Mysql_connect( 'localhost', 'root', 'root' ); //select db Mysql_select_db( 'test' ); //Set the character set to prevent garbled characters Mysql_query( 'set names "utf8"' ); //SQL $sql = "insert into `token` (string) values ('$data')"; //query Mysql_query( $sql ); $insert_id = mysql_insert_id(); If ( $insert_id ) { $state = 1; } else { $state = 0; } } ?> && $state ) { //Data insertion successful?> Inserted successfully Return ?>name="data" id="test" />
|
The html declaration, head and body are omitted. Compared with the initial code, it actually mainly realizes the actual insertion into the database and gives operation feedback (through the $state variable). You might as well copy the code yourself and try it out. (Of course, please modify the code in the database operation part according to your actual situation). The code is normal and the logic is OK, but there is a problem, that is, refreshing the page after displaying that the insertion is successful will execute the form processing action again and insert the data again! This is called the duplicate insertion problem. You can think about how to solve it yourself before releasing the solution.
Do you think that this problem is caused by receiving data and displaying the processing results on this page? Yes, you can think so. Using some debugging tools, you will find that the browser also retains the post data, so if you refresh the form after submitting it, the post data will be resubmitted.
If there is a way to clear the temporarily saved post data in the browser, the problem will be solved, but the server cannot do this, because this is the browser's own thing, or we will redirect Otherwise, refreshing will still result in repeated submission of data.
So far you may have understood the meaning of repeated submissions and the seriousness of the problem. If you do not choose redirection, you have to think of another solution, so this is the token solution.
Just as the token itself represents permissions, operation rights, identity marks, etc., can I add such an identity mark to my form and generate a token every time the client requests this form? Hook, make a judgment when submitting, and receive and process the form if it is correct. The essence of implementation is like this, and to reflect it in specific implementation, you need to use something called session. For session analysis, see wiki
The simple understanding is that session is also a concept of token, so you may be surprised, "What have I used the token?!", yes, but what we want to achieve is not just session but also On top of that, append some data to achieve the form token we want. So let's do it!
Session is also stored in the $_SESSION super global variable in PHP. Please use session_start() to enable it. The principle is the same for other server-side scripts, except that the calling method names may be inconsistent. The code after adding token is as follows:
代码如下 | 复制代码 |
//开启session session_start(); if ( isset( $_POST['submit'] ) && valid_token() ) { //表单 提交处理 } /** * 生成令牌 * @return string MD5加密后的时间戳 */ function create_token() { //当前时间戳 $timestamp = time(); $_SESSION['token'] = $timestamp; return md5( $timestamp ); } /** * 是否有效令牌 * @return bool */ function valid_token() { if ( isset( $_SESSION['token'] ) && isset( $_POST['token'] ) && $_POST['token'] == md5( $_SESSION['token'] ) ) { //若正确将本次令牌销毁掉 $_SESSION['token'] = ''; return true; } return false; } ?> 插入成功 返回
|
Part of the code paperen is omitted here because it is not the focus. In fact, there are only 3 things added:
First, add an input element before the end of the form. Remember the type is hidden (hidden field)
Second, two functions are added, create_token and valid_token, the former is used to generate tokens and the latter is used to verify tokens
Third, add one more condition in if, valid_token
Then you’re done, it’s very simple, and everything is gathered in the two newly added functions. The token used by paperen here is simply a timestamp. The timestamp when requesting the form is stored in $_SESSION['token']. Then the verification token will be clear, which is to check the $_POST['token submitted by the client. '] is consistent with $_SESSION['token'] after md5. Of course, it is also necessary to add the existence of the two variables $_POST['token'] and $_SESSION['token'].
You can encapsulate this simple token pattern to be more awesome and extend the functionality, such as adding form submission timeout verification. This is also a good opportunity to do it.
Finally, attach the Form_validation class file that paperen used to extend codeingeter, mainly to extend the token and form timeout. Welcome.php in the compressed package is the controller file, please place it in applicationcontroller (if you don’t want to add this controller, you can open it and copy the token method and put it in other existing controllers); please put MY_Form_validation.php in applicationlibraries .
codeingeter’s Form_validation class file code
The code is as follows | Copy code | ||||
public function index() { $this->load->view('welcome_message'); } public function token() { $this->load->helper( array('form') ); $this->load->library('form_validation'); If ( $this->input->post( 'submit' ) && $this->form_validation->valid_token() ) { //nothing //valid_token already contains the judgment of token timeout and token correctness. To enable token timeout, please set token_validtime to non-0 echo 'ok'; } //Generate form token $token = $this->form_validation->create_token(); //form example echo form_open(); echo form_input('token', ''); echo $token; echo form_submit('submit', 'submit'); echo form_close(); } } |
form_validation_token
The code is as follows | Copy code |
/** /** /** /** public function __construct() /** /** /** //Submitted hash if ( md5( $source_hash ) == $post_formhash ) /** |

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values and handle functions that may return null values.

In PHP, use the clone keyword to create a copy of the object and customize the cloning behavior through the \_\_clone magic method. 1. Use the clone keyword to make a shallow copy, cloning the object's properties but not the object's properties. 2. The \_\_clone method can deeply copy nested objects to avoid shallow copying problems. 3. Pay attention to avoid circular references and performance problems in cloning, and optimize cloning operations to improve efficiency.

PHP is suitable for web development and content management systems, and Python is suitable for data science, machine learning and automation scripts. 1.PHP performs well in building fast and scalable websites and applications and is commonly used in CMS such as WordPress. 2. Python has performed outstandingly in the fields of data science and machine learning, with rich libraries such as NumPy and TensorFlow.

Key players in HTTP cache headers include Cache-Control, ETag, and Last-Modified. 1.Cache-Control is used to control caching policies. Example: Cache-Control:max-age=3600,public. 2. ETag verifies resource changes through unique identifiers, example: ETag: "686897696a7c876b7e". 3.Last-Modified indicates the resource's last modification time, example: Last-Modified:Wed,21Oct201507:28:00GMT.

In PHP, password_hash and password_verify functions should be used to implement secure password hashing, and MD5 or SHA1 should not be used. 1) password_hash generates a hash containing salt values to enhance security. 2) Password_verify verify password and ensure security by comparing hash values. 3) MD5 and SHA1 are vulnerable and lack salt values, and are not suitable for modern password security.

PHP is a server-side scripting language used for dynamic web development and server-side applications. 1.PHP is an interpreted language that does not require compilation and is suitable for rapid development. 2. PHP code is embedded in HTML, making it easy to develop web pages. 3. PHP processes server-side logic, generates HTML output, and supports user interaction and data processing. 4. PHP can interact with the database, process form submission, and execute server-side tasks.

PHP has shaped the network over the past few decades and will continue to play an important role in web development. 1) PHP originated in 1994 and has become the first choice for developers due to its ease of use and seamless integration with MySQL. 2) Its core functions include generating dynamic content and integrating with the database, allowing the website to be updated in real time and displayed in personalized manner. 3) The wide application and ecosystem of PHP have driven its long-term impact, but it also faces version updates and security challenges. 4) Performance improvements in recent years, such as the release of PHP7, enable it to compete with modern languages. 5) In the future, PHP needs to deal with new challenges such as containerization and microservices, but its flexibility and active community make it adaptable.

The core benefits of PHP include ease of learning, strong web development support, rich libraries and frameworks, high performance and scalability, cross-platform compatibility, and cost-effectiveness. 1) Easy to learn and use, suitable for beginners; 2) Good integration with web servers and supports multiple databases; 3) Have powerful frameworks such as Laravel; 4) High performance can be achieved through optimization; 5) Support multiple operating systems; 6) Open source to reduce development costs.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 English version
Recommended: Win version, supports code prompts!

WebStorm Mac version
Useful JavaScript development tools

SublimeText3 Linux new version
SublimeText3 Linux latest version