PHP form Explanation

Source: Internet
Author: User
Tags form post php form
When it comes to web development, you have to mention HTML, which has been the de facto standard for Web user interface design for several years. While the use of page scripts such as Wap/xml makes it difficult to maintain HTML as a one-off scenario, developers still need to know the HTML language, especially the form portion of HTML, if they want to write a web app for front-end PHP.
In this chapter, we will study the following:
? Designing HTML forms with Dreamweaver
? Send and Receive form data using PHP
? The value and processing of multiple pages in PHP form
? Validating user input with PHP
? Prevent some lightweight attacks in PHP
? Two ways to manage your session in PHP: Cookies and session
? Plan for our web application
5.1 Forms and HTML
HTML is a simple markup language, providing users with a great deal of flexibility, which makes it easy to learn and write, but also because of this, too many web designers for HTML design and coding almost abuse, resulting in a page in IE, Firefox, Mozila several different browsers show the difference.
Today's web design has enabled new standards designed to make the HTML of a Web page contain only content and information, in a way that standard HTML and CSS (cascading style sheets) store information, which is now popular DIV+CSS design standards.
Some people recommend using XML instead of the HTML language. Although XML has such a powerful feature, but because the threshold of entry is high, daunting, and there are too many HTML sites, so the current line along the standard is HTML and XML compatible specifications, called XHTML, to transition from HTML to XML. The code in this book is based on XHTML compatibility, and it is recommended that you also apply XHTML to Web projects. Creating and working with forms is an important competency indicator for PHP developers. Let's start by describing how to design the form.
Forms are the most commonly used component in a web app, consisting of a submit button and other related elements. Forms are used in a variety of fields to implement functions such as registering users, filling in bank accounts, and logging in.
Forms use
As the start tag, to
End, otherwise it will not play any role. There are several forms that are allowed in an HTML page, with the form's name (name) and form ID as the distinction between them when writing.
Here is the simplest form, with the following code:

This form will only display a button "Submit query content" on the browser, not much meaning. If you want to submit your data and form a complete form, you need to
Tags add two more important attribute tags: action and method, as shown in the following form:

Where the action tag refers to the location of the file where the processing results are received, when the action value is empty, it is submitted to the current file itself, and if the action value is a different file or URL, it is submitted to the file or URL address processing.
The method label is the approach used to describe the data submitted, and it has two values: Get and post, and if the method property is not set or the property is null, the value of the browser default method is the Post method.
Here's how to process the post form.
Example 5-1:getpasswd.php– accept the value of a post form submission
$action = $_server[' php_self ');
if ($_server[' request_method '] = = ' POST ') {
Echo ' uses the Post method to pass form values ';
echo "$_post[email]";
}
?>

If you want to send the form or data to the server in your browser, you can do so using the Get or POST method. The Get method is to use the browser address bar to pass values when the URL is accessed. We can see this kind of URL string on many websites, and figure 5-1 shows the use of the Get method to pass parameters.

Figure 5-1
The Get method is convenient and intuitive, the disadvantage is that users who visit the site can also modify the URL string sent to the server, if the program is not good enough to be error-prone, and get pass string length can not exceed 250 characters, if long, the browser will automatically truncate, resulting in data loss. In addition, the Get method does not support any characters other than ASCII characters, such as the inclusion of Chinese characters or other non-ASCII characters, and requires additional encoding operations, although sometimes the browser can do it automatically (you can use the Url_encode and Url_decode functions, For details, see section 2.9.2).
When the Post method sends variable data, it is opaque to the user, and by HTTP protocol, the data is appended to the header of the header, and the user cannot modify it, which is much better for Web applications, and using post can send large volumes of data to the Web server.
Because post is sent with the header information of HTTP, the browser does not automatically resend post data when the post form is triggered and when the user clicks the Back button while browsing the page. If the user clicks the Refresh button at this point, there will be a "data has expired, whether to resubmit the form" prompt, which is not as easy as get use. When you use get to pass a value, the URL address of the browser still exists even if the user uses the back or refresh button.
As a result, we need to flexibly choose get and post to submit form data based on the actual application in development.
It is worth mentioning that if the form end tag is missing from the HTML, then the entire form will not trigger any commit action. In the actual development, some careless people will find that the click button does not reflect any, in fact, carefully check the form of the code, and sometimes even if you write less HTML characters, the browser will not work for us.
5.4 Form elements
There are more than 10 label elements used in the form, as shown in table 5-1 for commonly used and more important tags in PHP development.
Table 5-1
Form element Description
Input type= checkbox to allow the user to select multiple selections
Input type= The file browse box, which can be used to open a modal window to select a file when the file is uploaded
Input type= "hidden" hidden label for submitting variable values implicitly in a form
Input type= "password" Password text box, when the user enters a character in the text box will be replaced by the display as * number
Input type= "Radio" single option for setting up a set of selections where the user can select only one
Input type= "reset" clears and resets the form contents, which clears the contents of all text boxes in the form and restores the selection menu item to its original value
Input type= "submit" form Submit button
Input type= "text" single-line text box
Select drop-down list box, which can be single-selected and multi-selected. The default is single selection, if you add multiple selection functions, increase The option list drop-down menu, in conjunction with SELECT, displays the value textarea multiple lines of text box, and you need to close the text content between the labels when using the text box to form the following format: <textarea>your words.</textarea>
Where the hidden tag is known as a hidden or implied label, it does not appear on the user-browsed page interface, and can be used to pass some implied values when the user fills out a data form and spreads values between pages.
Password Password text box is used to hide the password, the user input text will be displayed in the text box, but the password is not encrypted, just replaced by the * display, please note.
The following describes the properties of the form, which are used to constrain the behavior or display of form elements in a form, and the meanings and constraints are shown in table 5-2.
Table 5-2
Property name Description
Name of the text box, based on the name, PHP establishes a key name in the Super Global array named as name
The width of the size text box, in the Select drop-down menu, indicates the number of options rows you can see
value in the Value text box, note that the value cannot be applied to the Type=password password text box and the Type=file file text box
Multiple This property is used in the drop-down menu select, which specifies that the user can use the CTRL and SHIFT keys to make multiple selections
Rows width of the number of character columns that can be accommodated when a multiline text box is displayed
cols height of character lines that can be accommodated when a multiline text box is displayed
In addition to some of the necessary attribute elements, there are some standard properties, such as Class,style,id, which can be found in HTML related materials.
In some dynamic scripts, you need to use PHP to generate form elements from a database based on different requests, so let's show several ways to generate form buttons or options.
1. Dynamically generates a set 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);
}
?>
The script will generate a list of radio button groups named city_id, with the default option of 024-"Shenyang".
2. Dynamically generate multi-option drop-down 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" and "movie",
"Internet" = "Internet",
"Travel" = "travel";
$html = generate_checkboxes ("Interests", $options, $interests);
?>
Choose your hobby:

3. Generates a multi-select drop-down menu.
$options = Array (
' 1 ' = ' Please select ',
' News ' = ' press ',
' Events ' = ' event ',
' Publications ' = ' manuscript '
);
$default = "News"; Default selected item
$html =generate_muilti_option ("Select", $options, $default);
Echo $html;
function Generate_muilti_option ($name, $options, $default) {
Create a list that allows multiple selections
Echo ' '; foreach ($options as $value = + $option) {echo 'if ($default = = $value) {echo ' selected ';} echo ' > '. Htmlspecialchars ($option). ''; } Echo '';
}
?>
Generally dynamically generated menus, many to get data from the database or array of data, converted to Dynamic HTML menu, can also be created manually.
5.5 How to handle forms
5.5.1 Check the origin of form submissions
Sometimes we need to deal with the source of the form submission, such as only allowing a host or submitting it to the script itself, preventing some people from forging the same form to commit to our program, causing security problems.
As we have described earlier, the PHP $_server Server Super Global array provides a variable called $_server[' Http_referer ') that holds the source of the previous page, such as the URL of a form submission or hyperlink. If someone submits a form from his computer or enters the current script name directly from the browser address, the variable saves the form source or is a null value, so that we can process it by its value.
The following example only allows the file itself to submit a form pass-through value.
Example 5-2:formreferer.php– judging 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 is:
$ref
The server address is:
$srv
--------------------------------------------------------------------------------
";
if (strcmp ($srv, $ref) = = 0) {
echo "Match";
} else{
echo "Do not allow off-site submissions";
}
}else{
Echo ' Please submit the form ';}
?>

There are several $_server server variables used in this example:
? Http_referer save a full source URL address.
? server_name the current server name.
? Php_self the full path of the current script, including the file name.
We can use the "HTTP/ == "To compare, if the same, it is a legitimate form submission, otherwise it will not be processed." Run example 5-2 script, click the "Submit" button after the result 5-2 is shown.

Figure 5-2
5.5.2 a complete form processing
We've already learned the easy way to work with forms in the previous step. Below we will create a complex form with the code shown below.

This form includes commonly used form elements: single-line text boxes, multiline text boxes, single options (radio), multiple options (checkboxes), and multiple-selection menus. The following is a detailed explanation.
? MaxLength is a property associated with a password text box that restricts the maximum length of a user's input password to 10 characters.
? The Age list box is a list menu that has its own values under its named properties. Selected is a specific attribute selection element that, if an option is appended with this property, is displayed as the first item in the display.
? Intro the contents of the text box, displays the text, row, and column widths by rows and cols.
? Fave_sport is a group of radio buttons (radio), we want to name the element by group, such as this group of radio buttons are called Fave_sport, the user can only select one, the sending script side only has a value.
? As with the single option, all multi-option members must have properties with the same name, and attribute names need to be added in parentheses [], so that the value of the multi-option is sent as an array to php,languages.
? The checked tag is a single option and a value in multiple options, which is already selected by default.
The above form is shown in screen 5-3.

Figure 5-3
Because the form form in the HTML above uses the Post method to pass the data, the data submitted by the user is saved to the Super Global array of $_post or $_request, and we can process the submitted data based on the values in the $_post array.
The data in the above form is submitted to the someform.php script, which has the following processing logic:
By judging whether the button's variable name is defined in $_post, if there is a representation that the form has been submitted
if (Isset ($_post["Btn_submit")) {
if (Empty ($_post[' username ')) {
echo "You did not enter the user name";
Exit (0);
}
if (Empty ($_post[' password ')) {
echo "You did not enter the password:";
Exit (0);
}
echo "Your username:". $_post[' user_name '). "
";
echo "Your password (clear text):". $_post[' password '). "
";
echo "Your Age:". $_post[' ages ']. "
";
if (!empty ($_post[' languages ')) {
echo "The language you have selected is:";
Array that is generated by the checkbox button that handles user selection interest
foreach ($_post[' languages ') as $lang) {
echo $lang. "";
}
} else {
echo "You did not enter any hobbies";
}
if (!empty ($_post[' develop_ide ')) {
echo "The development tool you are using is:";
Handles the array generated by the user's multi-select development Tools menu
foreach ($_post[' develop_ide ') as $ide) {
Echo $ide. " ";
}
} else {
echo "You did not choose the development tool";
}
echo "Your Self-Introduction:". NL2BR ($_post[' intro '). "
";
echo "page hidden value (passed by hidden Tag value):". $_post[' from ']. "
";
}
?>
Description: Use post to submit the form, pass the form data through the header part of the HTTP protocol, theoretically the size of the data has no upper limit. However, when using PHP for post submission, the file size is limited by the PHP config file (php.ini), we can modify the Post_max_size parameter in the php.ini file, can change the default 2M bytes to the size we need, but due to the characteristics of the HTTP protocol, This value should not be set too large, the maximum is 8M appropriate.
5.6 Other ways to work with forms
Let's look at two programming methods for working with forms and their pros and cons.
5.6.1 using the Import_request_variables () function
Use the Import_request_variables () function to selectively register a collection of global variables. You can use this function to import values for $_get, $_post, and $_cookie, and you can add a prefix (prefix) for each imported variable.
BOOL Import_request_variables (String types [, string prefix])
The types string in the parameter allows for any combination of G, p, c characters, or 3 characters. Where "G" represents a Get variable, "P" represents a post variable and "C" denotes a cookie.
Note: The order of 3 characters is different, when using "PG", the POST variable will overwrite the $_get variable with the same name, conversely, when using "GP", the $_get variable array will take precedence over $_post.
The prefix parameter is prefixed to the variable name and placed before all variables that are imported into the global scope. For example, if we have an array of $_get Super global variables called "userid" and we Provide "pref_" as a prefix, we will get a global variable named $pref_userid. If we are importing other global variables (such as the $_server variable), consider using the Extract () function (described in the function chapter). Note that when using the prefix prefix, do not conflict with existing data or variable names.
Examples of scripts that implement variable import using the Import_request_variable () function are as follows:
Import the value of the post commit variable, prefixed with Post_
Import_request_variable ("P", "Post_");
Import the variable values for Get and post submissions, prefixed with gp_,get priority over post
Import_request_variable ("GP", "Gp_");
Import the variable value of the cookie and get, and the cookie variable value takes precedence over the get
Import_request_variable ("CG", "cg_");
If we use the "PG parameter" in the Import_request_variables () function, consider the following script example:
if (Isset ($_request[' Btn_submit ')) {
echo "Normal get form Post variable value:". $_request[' Username '). "
";
Import_request_variables ("PG", "Import_");
Display the imported variable name
echo "Variable value imported using the Import_request_variables function:". $import _username;
}
?>

The form prompts the user to enter a name, completed and submitted, and the script will display the submitted name on the browser, as shown in 5-4.

Figure 5-4
Note: The prefix prefix parameter is required, and PHP throws a e_notice error if no prefix is specified, or if an empty string is specified as the variable prefix.
The Import_request_variables () function provides us with an intermediate method for the following situations:
1. When a user cannot use a super variable array;
2. When the register_globals parameter for the php.ini configuration file is off (the version after PHP 5 is off by default), use the Import_request_ Variables imports Get/post/cookie These array of super variables into the global scope.
3. At development time, you don't have to write $_get or $_request a bunch of long super global array names as long as you declare the range of variables introduced.
5.6.2 using the Extract () function
We can use the Extract () function, such as adding extract ($_post) to the front of the receiving page script, extract ($_get), and exporting a few 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 to a normal variable:
The variables obtained from the $_get and $_post Super variable arrays are converted to normal variables so that the variable names can be displayed directly
Extract ($_get);
Extract ($_post);
echo "Hello, $username $age";
?>

The implementation of interface 5-5 is shown.

5.7 Multiple pages passing data between
When encountering a very large form, it is not possible to put all the forms in a page, you need to break up a large form into several small forms, and saved in several pages, when the first form is completed, you need to collect the value of the form and pass it to the next form page.
We can do this with the following methods.
? Use the form's implied elements (hidden).
? Save the current form's data in the session (see chapter for details).
? Save the current form's data in the MySQL database.
You can choose a solution that is easy to process and debug from the above three scenarios. The value of the form can be used post, so that the size of the data transfer is not a problem, in addition, when debugging the program, we can see the HTML source file way to know whether the current variable is the expected value.
For a very large form, we have to think of ways to break them down into two or more forms to facilitate user input, which need to pass values between pages, the code is as follows:


When multiple pages pass data, we can use a statement like the one above to handle the former Kyoto net 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//www.ec80.cn/html/05/n-1705-6.html&aid=5526&sid= 6235007045042472&click=1&url=http%3a//www.bj135.com&v=0&s=http%3a//www.ec80.cn/html/05/ n-1705-7.html&rn=561758&k=%u4e00%u9875 "target=" _blank "> a page or a value passed by URL.
5.7 Multiple pages passing data between
When encountering a very large form, it is not possible to put all the forms in a page, you need to break up a large form into several small forms, and saved in several pages, when the first form is completed, you need to collect the value of the form and pass it to the next form page.
We can do this with the following methods.
? Use the form's implied elements (hidden).
? Save the current form's data in the session (see chapter for details).
? Save the current form's data in the MySQL database.
You can choose a solution that is easy to process and debug from the above three scenarios. The value of the form can be used post, so that the size of the data transfer is not a problem, in addition, when debugging the program, we can see the HTML source file way to know whether the current variable is the expected value.
For a very large form, we have to think of ways to break them down into two or more forms to facilitate user input, which need to pass values between pages, the code is as follows:


When multiple pages pass data, we can use a statement like the one above to process the previous page or the value passed through the URL.
5.9 Forms Safe
Site visitors are very diverse, he may be a student, may be a professor, may be a computer novice who do not know anything, more likely to be a hacker, whether it is to eject unexpected errors, or deliberately to find a ballast, they always like not to enter in the way we want, or to find our website security loopholes.
Some of the common vulnerabilities in the Web site are due to the developer's carelessness and, of course, partly because of the operating system or server configuration. Common security risks and proportions are shown in table 5-4.
Table 5-4
Program defect ratio
User input does not do validation 42.6%
Access control defect 3.6%
SESSION ID Validation Vulnerability 5.4%
Database SQL injection 28.6%

The above describes the PHP form, including the contents of the content, I hope that the PHP tutorial interested in a friend helpful.

  • 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.