Home > Backend Development > PHP Tutorial > Really solve the problem of repeated form submission php code_PHP tutorial

Really solve the problem of repeated form submission php code_PHP tutorial

WBOY
Release: 2016-07-13 10:47:50
Original
1124 people have browsed it

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

 代码如下 复制代码

   
method="post">
   


   
   
   


   


   
   


   
   

 代码如下 复制代码

http://localhost/mytest/token/form.php?data=test&submit=%E6%8F%90%E4%BA%A4

In this way, if I make a form directly and submit it to /test, the above agent is just a decoration, so how do we solve this problem If you already know how to solve it, then this article may not suit your taste. Paperen also plans to discuss it from the basics here, so if you want to see the solution in one step, it may not be suitable for you, so please pay attention. So~ let’s get started~ Paperen thinks you must know what a form is. The form element is a form. Generally, form elements must be used where input is required on web pages. It is also very common. The general code is as follows:
The code is as follows Copy code
         
Method="post">









The key point is actually the form and input elements. The p element is just added by paperen privately and has no impact on the subsequent explanation. It is actually very simple. The so-called input means input. You can completely understand the input element as being used by the user. Input is just that some attributes (type) cannot be used as input (here is submit), and the form element can be understood as a bag, which contains all user input data and is used to submit it back to the service. End processing, but what is worth noting about the form element is the method attribute. Generally speaking, there are two methods: get and post. In fact, don’t think too complicated (because you don’t need to understand it in depth, and it doesn’t have much to do with the subsequent content, such as If you are interested, you may want to use the browser's debugging tool to view the request header information and sending information, such as firebug). This shows that if you use get to submit the form, the values ​​​​of all input elements will appear in the address bar, while post will not. Yes, for example, the browser address bar after submitting this form using get
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
 代码如下 复制代码

if ( isset( $_POST['submit'] ) ) {
//表单提交处理
$data = isset(

$_POST['data'] ) ? htmlspecialchars( $_POST['data'] ) : '';
//connect
mysql_connect( 'localhost', 'root', 'root' );

//select db
mysql_select_db( 'test' );
//设置字符集防止乱码
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 ) { //数据插入成功 ?>

   

插入成功 返回

   

作 ?>

   

   

   

   

name="data" id="test" />

   

   

   

   

   

   

   

If ( isset( $_POST['submit'] ) ) {
//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
 代码如下 复制代码

class Welcome extends CI_Controller {


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已经包含令牌超时与令牌正确的判断,若要启用令牌超时,请将token_validtime设置为非0
                echo 'ok';
            }

            //生成表单令牌
            $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();
        }
}

<🎜>class Welcome extends CI_Controller {<🎜> <🎜>
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

/**
* @abstract Inherit CI’s Form_validation class and add tokens on its basis
​*/
class MY_Form_validation extends CI_Form_validation {

/**
* Token key value
* @var string
​​*/
var $key = 'token';
 
/**
* Form token validity time (seconds)
* @abstract If some forms need to limit the input time, set this value, if it is 0, there will be no limit
* @var int seconds
​​*/
var $token_validtime = 5;

/**
* Debug mode
* @var bool
​​*/
var $debug = false;

/**
* CI object
* @var
​​*/
private $_CI;

public function __construct()
{
        parent::__construct();
$this->_CI =& get_instance();
//If the configuration does not fill in encryption_key
         $encryption_key = config_item('encryption_key');
If ( empty( $encryption_key ) ) $this->_CI->config->set_item( 'encryption_key', $this->key );
​​​​ //If session is not loaded
If ( !isset( $this->_CI->session ) ) $this->_CI->load->library('session');
}

/**
*Set the token validity time
* @param int $second Number of seconds
​​*/
Public function set_token_validtime( $second )
{
           $this->token_validtime = intval( $second );
}

/**
* Get the form token validity time
* @return int seconds
​​*/
Public function get_token_validtime()
{
          return $this->token_validtime;
}

/**
* Verify whether the form token is legal
* @return bool
​​*/
Public function valid_token()
{
If ( $this->debug ) return true;
//Get the hash in session
$source_hash = $this->_CI->session->userdata( $this->key );
           if ( empty( $source_hash ) ) return false;
                             
//Determine whether it has timed out
If ( $this->is_token_exprie() ) return false;

//Submitted hash
$post_formhash = $this->_CI->input->post( $this->key );
           if ( empty( $post_formhash ) ) return false;

        if ( md5( $source_hash ) == $post_formhash )
        {
            $this->_CI->session->unset_userdata( $this->key );
            return true;
        }
        return false;
    }

    /**
* Generate form token (together with input element)
* @return string
​​*/
    public function create_token( $output = false )
    {
        $code = time() . '|' .  $this->get_random( 5 );
        $this->_CI->session->set_userdata( $this->key , $code);
        $result = function_exists('form_hidden') ? form_hidden( $this->key, md5( $code ) ) : '';
        if ( $output )
        {
            echo $result;
        }
        else
        {
            return $result;
        }
    }
   
    /**
* Get random numbers (can be expanded by yourself)
* @param int $number upper limit
* @return string
​​*/
    public function get_random( $number )
    {
        return rand( 0, $number );
    }
   
    /**
* Determine whether the form token has expired
* @return bool
​​*/
    public function is_token_exprie()
    {
        if ( empty( $this->token_validtime ) ) return false;
        $token = $this->_CI->session->userdata( $this->key );
        if ( empty( $token ) ) return false;
        $create_time = array_shift( explode('|', $token) );
        return ( time() - $create_time > $this->token_validtime );
    }
}

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/632826.htmlTechArticle以前看过很多各种防止表单重复提交js或jquery程序,但这种只是一个简单的方法,如果我们不从这个页面提交表单,直接找到接受数据的页面...
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template