PHP form details

Source: Internet
Author: User
Tags form post php form
: This article mainly introduces the PHP form details. if you are interested in the PHP Tutorial, you can refer to it. When talking about Web development, we have to mention HTML, which has been a de facto standard for Web user interface design for several years. Although the use of WAP, XML, and other page scripts makes it difficult to maintain HTML as a stand-alone situation, developers still need to understand the HTML language to compile front-end PHP Web applications, especially the HTML form section.
In this chapter, we will learn the following:
? Use Dreamweaver to design HTML forms
? Use PHP to send and receive form data
? Transfer and processing of multiple pages in a PHP form
? Use PHP to verify user input
? Prevent some lightweight attacks in PHP
? Two php session management methods: COOKIE and SESSION
? Plan our Web applications
5.1 form and HTML
HTML is a simple markup language that provides users with great flexibility. This makes it easy to learn and write, too many web designers almost abuse HTML design and coding, resulting in a page displayed in different browsers such as IE, Firefox, and Ila.
Today's Web design has enabled new standards to make the HTML of a webpage only contain content and information and store information in standard HTML and CSS (Cascading Style Sheets, that is, the currently popular design standard for DIV + CSS.
Some people suggest replacing the HTML language with XML. Although XML has such powerful functions, it is daunting because of its high entry threshold. At present, there are too many HTML websites, therefore, the frontend line is compatible with HTML and XML, which is called XHTML, used to transition from HTML to XML. The code in this book is based on XHTML compatibility. we recommend that you also apply XHTML to Web projects. Creating and processing forms is an important capability indicator for PHP developers. The following describes how to design a form.
A form is the most common component in a Web application. it consists of a submit button and other related elements. Forms are applied in various fields for registering users, filling in bank accounts, and logging in.
Form usage
As the start tag
Otherwise, it will not have any effect. Several forms are allowed in an HTML page, and the names and IDs of the forms are used as the differences between them.
The following is the simplest form. the code is as follows:

This form only displays the "Submit query content" button in the browser, which does not make much sense. To submit data and form a complete form, you must
Add two more important property Tags: action and method, as shown in the following table:

Here, the action tag refers to the location of the file that receives the processing result. if the action value is blank, it is submitted to the current file. if the action value is another file or URL, the file or URL address is submitted for processing.
The method label describes the method used for data submission. It has two values: GET and POST. if the method attribute is not set or the attribute is null, the default method value of the browser is the POST method.
The following describes how to process the POST form.
Example 5-1: getPasswd. php-accept the value submitted by the POST form
$ Action = $ _ SERVER ['php _ SELF '];
If ($ _ SERVER ['request _ method'] = 'post '){
Echo 'use the POST method to pass the form value ';
Echo "$ _ POST [email]";
}
?>

If you want to send forms or data to the server in a browser, you can use the GET or POST method. The GET method uses the address bar of the browser to pass the value when accessing the URL. We can see this type of URL string on many websites.-1 shows passing parameters using the GET method.

-1
The GET method is convenient and intuitive. The disadvantage is that users who access the website can modify the URL string and send it to the server. if the program is not well processed, it is easy to make mistakes, in addition, the length of the string passed by GET cannot exceed 250 characters. if it is too long, the browser automatically truncates the string, leading to missing data. In addition, the GET method does not support any characters other than ASCII characters. for example, if the GET method contains Chinese characters or other non-ASCII characters, additional encoding is required, although sometimes the browser can also do it automatically (you can use the url_encode and url_decode functions. for details about how to use them, see section 2.9.2 ).
When the POST method sends variable data, it is not transparent to users. for HTTP protocol, the data is appended to the header information and cannot be modified at will. for Web applications, the security is much better, and you can use POST to send large volumes of data to the Web server.
Because POST is sent along with the HTTP header information, after the POST form is submitted, if the user clicks the "back" button when browsing the page, the browser will not automatically resend the POST data. If you click "refresh", a message "data has expired and whether to resubmit the form" is displayed, which is not as convenient as GET. When using GET to pass values, even if you use the "back" or "refresh" button, the URL address of the browser still exists.
Therefore, in development, we need to flexibly select GET and POST based on actual applications to submit form data.
It is worth mentioning that if the form end tag is missing in HTML, the entire form will not trigger any submission action. During actual development, some careless people will find that clicking the button does not reflect any. In fact, you can check the form code carefully. sometimes, even if you write less than one HTML character, browsers won't work for us either.
5.4 form elements
There are more than a dozen tag elements used in the form. commonly used and important tags in PHP development are shown in Table 5-1.
Table 5-1
Form element description
Input type = "checkbox" check box, allowing users to select multiple options
Input type = "file" file browser. when a file is uploaded, you can open a mode window to select a file.
Input type = "hidden" hide tag, used to implicitly submit variable values in the form
Input type = "password" text box. when you enter a character in this text box, the text box is replaced with the * character.
Input type = "radio" single option, used to set a group of selection items, you can only select one
Input type = "reset" clears and resets the form content, which is used to clear the content of all text boxes in the form and restores the selected menu item to the initial value.
Input type = "submit" form submit button
Input type = "text" single-line text box
Select drop-down list box, which can be single-choice or multiple-choice. The default option is single-choice. if multiple options are added You can.Option list drop-down menu, used with select, display the value for selectionWhen using a text box, you must close the text content between labels to form the following format: Your text
The hidden tag is called a hidden or hidden tag. it does not appear on the page that the user browses. when you enter a value between the data form and the cross-page, you can use this label to pass some implicit values.
The password text box is used to hide the password. The text entered by the user will be displayed as * in the text box, but the password is not encrypted. it will only be replaced by *. note this.
The following describes the attributes of a form. they are used to constrain the behavior or display of form elements in a form. their meanings and constraints are shown in Table 5-2.
Table 5-2
Attribute name description
Name of the name text box. PHP creates a name-based key name in the Super Global array.
The width of the size text box. in the select drop-down menu, you can see the number of option lines.
The default value in the value text box. Note that this value cannot be applied to the type = password text box or the type = file text box.
Multiple this attribute is used in the select drop-down list menu. you can use Ctrl and Shift to select multiple options.
Width of the number of columns that can be accommodated when the rows multi-line text box is displayed
Height of the number of lines that can be accommodated when the cols multi-line text box is displayed
In addition to the necessary attribute elements, some standard attributes such as class, style, and id can be found in HTML.
In some dynamic scripts, you need to use PHP to generate form elements from the database according to different requests. below we will show several ways to generate form buttons or options.
1. dynamically generate a group of radio buttons.
$ Options = array ("010" => "Beijing ",
"020" => "Shanghai ",
"024" => "Shenyang ",
"0411" => "Dalian ");
$ Default = "024 ";
$ Html = generate_radio_group ("city_id", $ options, $ default );
Echo $ html;
Function generate_radio_group ($ name, $ options, $ default = ""){
$ Name = htmlentities ($ name );
Foreach ($ options as $ value => $ label ){
$ Value = htmlentities ($ value );
$ Html. =" If ($ value = $ default ){
$ Html. = "CHECKED ";
}
$ Html. = "NAME = \" $ name \ "VALUE = \" $ value \ "> ";
$ Html. = $ label ."
";
}
Return ($ html );
}
?>
This script will generate a single-choice button group named city_id. the default option is 024-"Shenyang ".
2. dynamically generate a multi-option drop-down list menu.
Function generate_checkboxes ($ name, $ options, $ default = array ()){
If (! Is_array ($ default )){
$ Default = array ();
}
Foreach ($ options as $ value => $ label ){
$ Html. =" If (in_array ($ value, $ default )){
$ Html. = "checked ";
}
$ Html. = "name = \" {$ name} [] \ "value = \" $ value \ "> ";
$ Html. = $ label ."
";
}
Return ($ html );
}
$ Interests = array ("music" => "music ",
"Movie" => "movie ",
"Internet" => "Internet ",
"Tourism" => "tourism ");
$ Html = generate_checkboxes ("interests", $ options, $ interests );
?>
Select your hobbies:

3. generate a multi-choice drop-down list menu.
$ Options = array (
'1' => 'Select ',
'News' => 'news ',
'Events' => 'event ',
'Publications '=> 'Manuscript'
);
$ Default = "news"; // items selected by default
$ Html = generate_muilti_option ("select", $ options, $ default );
Echo $ html;
Function generate_muilti_option ($ name, $ options, $ default ){
// Create a list ticket that allows multiple selections
Echo' ';Foreach ($ options as $ value => $ option ){Echo'If ($ default = $ value ){Echo 'selected ';}Echo '>'. htmlspecialchars ($ option ).'';}Echo'';
}
?>
Generally, dynamically generated menus are mostly data or data arrays obtained from databases and converted to Dynamic HTML menus. you can also create them manually.
5.5 form handling method
5.5.1 check the source of form submission
Sometimes, we need to process the source of form submission. for example, we can only submit a host or to the script itself to prevent some people from submitting the same form to our program, security issues.
As we mentioned earlier, the $ _ SERVER Super global array of PHP provides a variable named $ _ SERVER ['http _ referer'] to save the source of the previous page, for example, the URL of form submission or hyperlink. If someone submits a form from his computer or directly enters the name of the current script from the browser address, the variable saves the form source or is empty, in this way, we can use its value for processing.
The following example only allows the file to submit the form to pass the value.
Example 5-2: formreferer. php-judge the form source address
$ Action = $ _ SERVER ['php _ SELF '];
If ($ _ SERVER ['request _ method'] = 'post '){
$ Ref = $ _ SERVER ['http _ referer'];
$ Srv = "http: // {$ _ SERVER ['server _ name']} $ action ";
Echo "current source:
$ Ref
The server address is:
$ Srv
--------------------------------------------------------------------------------
";
If (strcmp ($ srv, $ ref) = 0 ){
Echo "match ";
} Else {
Echo "external site submission not allowed ";
}
} Else {
Echo 'submit the form ';}
?>

In this example, the $ _ SERVER variables are as follows:
? HTTP_REFERER saves a complete source URL.
? The current server name of SERVER_NAME.
? PHP_SELF: the complete path of the current script, including the file name.
We can use "http :// = If they are the same, it is a legal form submission, otherwise it will not be processed. Run the sample 5-2 script and click Submit. The result is 5-2.

-2
5.5.2 process a complete form
We have learned a simple way to process a form. The following code creates a complex form.

This form includes common form elements: single-line text box, multi-line text box, single option (radio), multi-option (checkbox), and multi-choice menu. The following is a detailed description.
? Maxlength is an attribute associated with the password text box. it limits the maximum length of a password to 10 characters.
? The age list box is a list menu with its own values under its naming attributes. Selected is a specific attribute selection element. If an option is attached with this attribute, this attribute is listed as the first item during display.
? The content in the intro text box displays text, row, and column width according to rows and cols.
? Fave_sport is a set of single-choice buttons (radio). we need to name the elements by group. for example, each group of single-choice buttons is named fave_sport. you can select only one, the sending script also has only one value.
? Like a single option, all multi-option members must have attributes of the same name, and the attribute name must be added with brackets []. in this way, the values of multiple options are sent to PHP in an array, ages is in this form.
? The checked tag refers to a value in a single option and multiple options. it is selected by default.
The Figure 5-3 in the form above is shown.

-3
Because the form in the preceding HTML uses the POST method to transmit data, the data submitted by the user is saved to the Super global array of $ _ POST or $ _ REQUEST, we can process submitted data based on the value in the $ _ POST array.
Submit the data in the preceding form to the someform. php script. the processing logic of this script is as follows:
// Determine whether the variable name of the button is defined in $ _ POST. If yes, the form has been submitted.
If (isset ($ _ POST ["btn_submit"]) {
If (empty ($ _ POST ['username']) {
Echo "you have not entered the user name ";
Exit (0 );
}
If (empty ($ _ POST ['password']) {
Echo "you have not entered the password :";
Exit (0 );
}
Echo "Your username:". $ _ POST ['User _ name']."
";
Echo "your password (plaintext):". $ _ POST ['password']."
";
Echo "your age:". $ _ POST ['age']."
";
If (! Empty ($ _ POST ['ages ']) {
Echo "the language you selected is :";
// Process the array generated by the checkbox button of interest selected by the user
Foreach ($ _ POST ['ages '] as $ lang ){
Echo $ lang ."";
}
} Else {
Echo "you have not entered any interests ";
}
If (! Empty ($ _ POST ['develop _ ide ']) {
Echo "your development tool is :";
// Process the array generated by the menu of multiple development tools selected by the user
Foreach ($ _ POST ['develop _ ide '] as $ ide ){
Echo $ ide ."";
}
} Else {
Echo "you have not selected a development tool ";
}
Echo "your self-introduction:". nl2br ($ _ POST ['Intro'])."
";
Echo "webpage hidden value (passed through the hidden tag value):". $ _ POST ['from']."
";
}
?>
Note: The form is submitted in POST mode and the form data is transmitted through the header part of the HTTP protocol. Theoretically, the data size is unlimited. However, when using PHP for POST submission, the file size is subject to the PHP configuration file (php. ini) restrictions, we can modify php. the post_max_size parameter in the INI file can be changed to the default size of 2 MB. However, due to the characteristics of the HTTP protocol, this value should not be too large, and the maximum value is 8 MB.
5.6 Other forms processing methods
Next, let's take a look at the two forms processing programming methods and their advantages and disadvantages.
5.6.1 use the import_request_variables () function
You can use the import_request_variables () function to selectively register a global variable set. You can use this function to import values of $ _ GET, $ _ POST, and $ _ COOKIE, and add prefix for each imported variable ).
Bool import_request_variables (string types [, string prefix])
The types string in the parameter can contain any combination of g, p, c, or 3 characters. "G" indicates the GET variable, "p" indicates the POST variable, and "c" indicates the cookies.
Note: The Order of the three characters varies. when "pg" is used, the POST variable overwrites the $ _ GET variable with the same name. otherwise, when "gp" is used, the $ _ GET variable array takes precedence over $ _ POST.
Prefix is used as the prefix of the variable name and placed before all variables imported to the global scope. For example, if we have an array of $ _ GET super global variables named "userid" and "pref _" is provided as the prefix, we will GET a global variable named $ pref_userid. If you want to import other global variables (for example, $ _ SERVER variables), consider using the extract () function (described in the function chapter ). Note: do not conflict with existing data or variable names when prefix is used.
An example of the script for using the import_request_variable () function to import variables is as follows:
// Import the variable value submitted by POST, prefixed with post _
Import_request_variable ("p", "post _");
// Import the variable values submitted by GET and POST. the prefix is gp _. GET takes precedence over POST.
Import_request_variable ("gp", "gp _");
// Import the Cookie and GET variable values. the Cookie variable value takes precedence over GET
Import_request_variable ("cg", "cg _");
If we use the "pg parameter" in the import_request_variables () function, see the following script example:
If (isset ($ _ REQUEST ['btn _ submit ']) {
Echo "normally obtained form POST variable value:". $ _ REQUEST ['username']."
";
Import_request_variables ("pg", "import _");
// Display the name of the imported variable
Echo "variable value imported using the import_request_variables function:". $ import_Username;
}
?>

This form prompts you to enter a name. after the name is submitted, the script displays the submitted name in the browser, as shown in Figure 5-4.

-4
Note: the prefix parameter is required. if the prefix is not specified or an empty string is specified as the variable prefix, PHP will throw an E_NOTICE error.
The import_request_variables () function provides an intermediate method for the following scenarios:
1. when the user cannot use the super variable array;
2. in php. when the register_globals parameter of the ini configuration file is Off (the default version after PHP 5 is Off), use import_request_variables to import the GET/POST/Cookie Super variable arrays to the global scope.
3. during development, as long as the scope of the introduced variables is declared, you do not need to write $ _ GET or $ _ REQUEST a bunch of long Super Global array names.
5.6.2 use the extract () function
We can use the extract () function, for example, adding the extract ($ _ POST); extract ($ _ GET); statement at the beginning of the script receiving page, export several Super variable array values for form processing, as shown in the following code:
@ Extract (I _addslashes ($ _ POST), EXTR_OVERWRITE );
@ Extract (I _addslashes ($ _ GET), EXTR_OVERWRITE );
@ Extract (I _addslashes ($ _ COOKIE), EXTR_OVERWRITE );
@ Extract (I _addslashes ($ _ SESSION), EXTR_OVERWRITE );
Let's look at a script example that uses extract to export normal variables:
// Convert the variables obtained from the $ _ GET and $ _ POST Super variable arrays to normal variables, so that the variable name can be directly displayed.
Extract ($ _ GET );
Extract ($ _ POST );
Echo "Hello, $ username $ age ";
?>

The implementation interface is shown in Figure 5-5.

Data transfer between more than 5.7 pages
When a very large form is encountered, it is impossible to put all the forms in one page. a large form must be divided into several small forms and saved in several pages, after the first form is filled in, you need to collect the value of the form and pass it to the next form page.
We can use the following method for processing.
? Use the hidden element of the form ).
? Store the data of the current form in the SESSION (for details, see the SESSION chapter ).
? Store the data of the current form in the MySQL database.
You can select a solution that is easy for program processing and debugging from the above three solutions. You can use POST to pass the value of a form. in this way, the size of the transmitted data is not a problem. In addition, when debugging a program, we can view the HTML source file, to know whether the current variable is the expected value.
For a very large form, we need to find a way to break them into two or more forms to facilitate user input. This requires passing values between pages. the code is as follows:


When multiple pages pass data, we can use statements similar to the above to process the previous Kyoto City network www.bj135.com@Vogate.com "STYLE =" border-bottom: 1px dotted rgb (255, 51,102 ); font-size: 1em; cursor: pointer; color: rgb (255, 51,102); text-decoration: underline; "HREF =" http://action.vogate.com/c/c.php? R = http % 3A // Values "TARGET =" _ blank "> values transmitted on one page or by URL.
Data transfer between more than 5.7 pages
When a very large form is encountered, it is impossible to put all the forms in one page. a large form must be divided into several small forms and saved in several pages, after the first form is filled in, you need to collect the value of the form and pass it to the next form page.
We can use the following method for processing.
? Use the hidden element of the form ).
? Store the data of the current form in the SESSION (for details, see the SESSION chapter ).
? Store the data of the current form in the MySQL database.
You can select a solution that is easy for program processing and debugging from the above three solutions. You can use POST to pass the value of a form. in this way, the size of the transmitted data is not a problem. In addition, when debugging a program, we can view the HTML source file, to know whether the current variable is the expected value.
For a very large form, we need to find a way to break them into two or more forms to facilitate user input. This requires passing values between pages. the code is as follows:


When data is transmitted on multiple pages, we can use statements similar to the preceding statements to process values transmitted on the previous page or through URLs.
5.9 form security
The visitor to the website is very different. He may be a student, a professor, a computer Cainiao who doesn't know anything, or a hacker, whether it's an unexpected error or an intentional fault, they always prefer not to enter the information as expected, or find security vulnerabilities on our website.
Some common vulnerabilities on websites are often caused by developers' carelessness. of course, they are also caused by operating system or server configuration. Common security risks and proportions are shown in Table 5-4.
Table 5-4
Program defect examples
User input is not verified 42.60%
Access control defect 3.60%
Session id verification vulnerability 5.40%
Database SQL injection of 28.60%

The above describes the PHP form details, including the content, hope to be helpful to friends who are interested in the PHP Tutorial.

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.