search
HomeBackend DevelopmentPHP TutorialReally 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
 代码如下 复制代码

// 第一次提交
  checkSubmitFlg = true;
  return true;
 } else {

//重复提交
  alert("Submit again!");
  return false;
 }
}

//以下三种方式分别调用

//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程序,但这种只是一个简单的方法,如果我们不从这个页面提交表单,直接找到接受数据的页面...
Statement
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
How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

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.

How does PHP handle object cloning (clone keyword) and the __clone magic method?How does PHP handle object cloning (clone keyword) and the __clone magic method?Apr 17, 2025 am 12:24 AM

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 vs. Python: Use Cases and ApplicationsPHP vs. Python: Use Cases and ApplicationsApr 17, 2025 am 12:23 AM

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.

Describe different HTTP caching headers (e.g., Cache-Control, ETag, Last-Modified).Describe different HTTP caching headers (e.g., Cache-Control, ETag, Last-Modified).Apr 17, 2025 am 12:22 AM

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.

Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1?Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1?Apr 17, 2025 am 12:06 AM

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: An Introduction to the Server-Side Scripting LanguagePHP: An Introduction to the Server-Side Scripting LanguageApr 16, 2025 am 12:18 AM

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 and the Web: Exploring its Long-Term ImpactPHP and the Web: Exploring its Long-Term ImpactApr 16, 2025 am 12:17 AM

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.

Why Use PHP? Advantages and Benefits ExplainedWhy Use PHP? Advantages and Benefits ExplainedApr 16, 2025 am 12:16 AM

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.

See all articles

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)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

DVWA

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

SublimeText3 English version

Recommended: Win version, supports code prompts!

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version