Home >Backend Development >PHP Tutorial >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 ) /** |