Analysis and Comparison of four Form Verification Methods

Source: Internet
Author: User
Tags php server

For interactive sites, quick, efficient, and user-friendly form verification is conducive to user experience and site maintenance. This article mainly analyzes and compares the advantages and disadvantages of the Form Verification Method, and obtains the applicable scenarios of each method.

Preface

Any site that can interact with each other has an input form. If possible, the data entered by the user should be verified. No matter what system the backend of the server is, it is unwilling to waste time on some invalid information. It is necessary to verify the form data. If there is any form input that does not comply with the rules, prompt information should be returned in a timely manner. This article lists four form verification methods with different principles and provides implementation of each method on the PHP server.

 



Back to Top

Browser Verification

Traditionally, form data is generally verified by JavaScript on the browser. The browser performs fast verification. If any input does not meet the requirements, the response is returned to the user quickly. Because the verification data does not need to be submitted to the server, it does not increase the load on the server. As shown in process 1 of browser-side verification, the form is submitted. If the verification succeeds, the form is submitted to the server for processing. If the verification fails, the form is returned to the user.

Figure 1. Schematic diagram of browser-side Verification

The source code of various form verification methods provided in this article takes a simple form as an example. The form contains two text input boxes, "username" and "password", and a "Submit" button. Code List 1 provides an example of browser-side JavaScript verification. If the input "username" or "password" does not meet the requirements, the system prompts the user in the pop-up box, returns false, and stops form submission.

Listing 1. browser-side JavaScript Verification Code

   function validform(thisForm)    {       error_string = "";       if((message=checkusername(thisForm.username))!="")         {           error_string="UserName:"          error_string += message;           alert(error_string);           return false;          }       if((message = checkpassword(thisForm.pass))!="")         {           error_string="Password:"          error_string += message;           alert(error_string);           return false;          }          return true;    } 

 

As shown in figure 1, this form verification method has a fatal disadvantage. Many tools can intercept form data after Form Verification and before the browser sends a request. Attackers can modify the data in the request, attackers can bypass Javascript and inject malicious data into the server. This increases the chance of XSS attacks. For general websites, the Form Verification Method on the browser is not supported.

 



Back to Top

Verify both browser and Server

The browser-side and server-side dual verification method adds server-side Verification Based on the browser-side verification method. Its principle 2 shows that this method adds server-side verification, which makes up for the shortcomings of traditional browser-side verification. If the form input does not meet the requirements, the browser-side JavaScript verification can quickly respond, while the server-side verification can prevent malicious users from bypassing JavaScript verification to ensure the accuracy of the final data.

Figure 2. Dual-validation principle of browser and Server

In addition to client JavaScript verification, this method adds PHP verification on the server. The sample code is shown in List 2. checkusername () and checkpassword () are two verification interface functions written in PHP, determine the validity of the form based on the $ error result.

List 2. php verification of Server Forms

   if(isset($_POST['username']))  {   $usermsg  = checkusername($_POST['username']);   if($usermsg != '')     $error = true;   if(isset($_POST['pass']))   {     $passmsg = checkpassword($_POST['pass']);     if($passmsg != '')     $error = true;   }  } 

 

The disadvantages of this method are clear at a glance. You must maintain two codes to implement the same functions, which increases the workload of developers and is not conducive to subsequent development. The browser-side and server-side dual verification methods also pose a risk. For some form verification rules, the server may not want to disclose them to users, and the browser copies the server-side verification function, publish verification rules to users.

 



Back to Top

Server Verification

Considering the above two verification methods, we now consider using the server-side verification method. The structure of this method is very simple, as shown in principle 3. The client submits the form and verifies the form on the server. If error data is found, the form page is returned and the error message is added to the same page. If the verification is successful, the form is processed.

Figure 3. server-side verification schematic

In this method, when an illegal input is required to return the form, in addition to loading the error message on this page, you must also note that the form content must maintain the user input when the form is submitted, in this way, the user can associate the incorrect form input with the error prompt information to help the user fill in the correct input. The appendchild function in DOM technology can be used to append relevant error prompts. Its implementation is shown in code listing 3. For the effect, see Figure 4.

Listing 3. Using DOM technology to implement prompt information code

   find_obj = document.getElementsByName("username");   var sp1 = document.createElement('span');   sp1.className= 'formerror';   sp1.appendChild(document.createTextNode(usermsg));   find_obj[0].parentNode.appendChild(sp1);   find_obj = document.getElementsByName("pass");   var sp2 = document.createElement('span');   sp2.className= 'formerror';   sp2.appendChild(document.createTextNode(passmsg));   find_obj[0].parentNode.appendChild(sp2); 

Figure 4. loading error messages

Because the verification is handled by the server, the input response speed of this method is not as fast as that of the browser, which is mainly affected by the busy network and server load. At the same time, if other forms on the same page are time-consuming, the response time of this return PAGE method will be further increased.

 



Back to Top

Ajax-based verification

The Form Verification Technology Based on AJAX technology combines the advantages of server-side verification, browser-side and server-side dual verification methods, and discards the disadvantages of both. The server-side verification method has a clear structure to prevent malicious attacks. The main problem is that if the error form information is entered, the entire page needs to be re-transmitted. If the same page has multiple forms, returning the entire page may increase the user's waiting time. The browser and server verify that the response speed is fast. The problem is code redundancy.

The Ajax-based verification method also requires two verifications: first, feedback verification, regardless of whether the form data is accurate or not, the server provides feedback information, the function is equivalent to browser-side authentication in dual authentication. The verification before form processing prevents malicious modification. Its function is equivalent to server-side authentication in dual authentication. Principle 5: Once a form is submitted, a form information field is constructed and sent to the Ajax engine for verification on the server side. The server sends the verification result to the user, and the client sends the feedback information, determine whether the form input is normal. In Ajax technology, all the above operations are performed in the background without affecting the status of the forms on the current page. If the input is invalid, the system returns a message to the user. If the input is normal, the client submits the form in the normal way. To prevent malicious modification, form verification is required before processing. This step shares the Code with the previous verification.

Figure 5. Schematic diagram of Ajax-based verification

For more information about Ajax technology, see the series of articles on developerworks. One of the core concepts of AJAX is the XMLHTTPRequest object, which is a JavaScript Object. When creating this object, various browser methods are different. For specific implementation, refer to the source code.

Feedback Verification involves two main issues: first, constructing verification fields, and second, the format of feedback information.

Because the verification field shares the verification code with the normal form field, the format of the verification field fully complies with the format when the form is submitted. Code for constructing verification fields for a form is shown in Listing 4. The checkflag field is used to distinguish between two types of verification.

Listing 4. Build verification field code

   var postData = "";  var fields = form.elements;  for (var i=0; i < fields.length; i++) {  if (fields[i].name != "") {   type = fields[i].type;    if ((type == 'radio') || (type == 'checkbox')) {    if (!fields[i].checked) { continue; }     }  if ((type == 'submit')&&(!(fields[i].name == submitName))) {    continue;  }  if (postData) { postData += "&"; }  postData += fields[i].name + "=" + encodeURIComponent(fields[i].value);           }  }      postData += "&checkflag=1"; 

 

Feedback information is mainly processed in browser Javascript. Different formats require different processing methods. In traditional Ajax dynamic page processing, the feedback information contains a large amount of information. The XML format can be used to process and simplify the program by using DOM technology. In this example, the feedback information only contains the verification result information, and the simple data format can meet the requirements. The client's JavaScript analyzes the feedback information and determines whether to submit the complete form based on the results, for specific implementation, see source code.

The Ajax-based verification method code is relatively complex. The incorrect form requires two network interactions, and the correct submission requires three network interactions. The response time of this verification method has a great relationship with the Network busy degree. Compared with server-only verification, this method does not need to download the entire page again during the verification phase. When multiple forms exist on the same page, the Ajax-based verification method does not affect other forms on the same page.

 



Back to Top

Summary

The above four verification methods have their own advantages and disadvantages. You should select different methods as needed. The browser-side verification method is applicable to scenarios where the form input requirements are not particularly strict. The browser-side and server-side dual verification are widely used, but this method is not conducive to subsequent development; the server-side verification method has a simple structure, but the development code is relatively complex. The Ajax-based verification method has high requirements on the network, but the method has a clear structure, form Verification is separated from form processing, but the verification code is shared to simplify the work of developers.



Back to Top

Download

Description Name Size Download Method
Sample Code Code.zip 2.8kb {
Sa_onclick (this. href)
} "Onkeypress =" function onkeypress ()
{
Sa_onclick (this. href)
} "Href =" http://writeblog.csdn.net/code.zip ">HTTP
Information about the Download Method

References

  • This article describes how to avoid XSS attacks on Web applications built using PHP.
  • View the "PHP function manual" to learn about PhP interface functions and usage.
  • Use the DOM tutorial to learn how to use the Dom.
  • Refer to the Ajax series on developerworks to learn about Ajax.
  • Developerworks technical events and network broadcasts: Stay tuned to developerworks technical events and network broadcasts.
  • Developerworks Web Development Area: extends your skills in website development through articles and tutorials dedicated to Web technology.

About the author

 

Hu lixia, a software engineer at IBM China Development Center, is mainly engaged in bladecenter-related development and testing.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.