Detailed explanation of PHP forms

WBOY
Release: 2016-07-29 09:09:05
Original
1890 people have browsed it

When it comes to Web development, we have to mention HTML, which has been the de facto standard for Web user interface design for several years. Although the current use of page scripts such as WAP/XML makes it difficult to maintain the dominance of HTML, if you want to write front-end PHP web applications, developers still need to understand the HTML language, especially the form part of HTML.
In this chapter, we will learn the following:
? Use Dreamweaver to design HTML forms
? Use PHP to send and receive form data
? PHP form multi-page value transfer and processing
? Use PHP to verify user input
? Prevent in PHP Some lightweight attacks
? Two session management methods of PHP: COOKIE and SESSION
? Planning our web applications
5.1 Forms and HTML
HTML is a simple markup language that provides users with great Flexibility, which makes it easy to learn and write. It is also because of this that too many web designers almost abuse the design and coding of HTML, causing a page to run in several different browsers such as IE, Firefox, and Mozila. shown to be very different.
Today’s web design has enabled new standards, aiming to make the HTML of web pages only contain content and information, and store information in standard HTML and CSS (cascading style sheets), which is the now popular DIV+CSS design standard.
Some people suggest using XML to replace HTML language. Although XML has such powerful functions, the entry barrier is high and daunting, and there are currently too many HTML-based websites. Therefore, the current standard is the compatible specification of HTML and XML, called XHTML, which is used 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 processing forms is an important competency indicator for PHP developers. Next we start to introduce how to design the form.
Forms are the most commonly used components in web applications, consisting of submit buttons and other related elements. Forms are used in various fields to implement functions such as registering users, filling in bank accounts, and logging in.
The form uses
as the start tag and ends with
, otherwise it will have no effect. Several forms are allowed in an HTML page, and the name and Form ID of the form are used as the distinction between them when writing.
The following is the simplest form, the code is as follows:




This form will only display a button on the browser "Submit query content" "The words don't have much meaning. If you want to submit data and form a complete form, you need to add two important attribute tags to the
tag: action and method, as shown in the following form:

Email:


where the action tag refers to the file location that receives the processing result. When the action value is empty, it is submitted to the current file itself. If the action value is other file or URL, then submit it to the file or URL address for processing. The
method tag describes the method used when submitting data. It has two values: GET and POST. If the method attribute is not set or the attribute is empty, the browser defaults to the POST method.
Here’s how to handle POST forms.
Example 5-1: getPasswd.php – Accept values ​​submitted by POST form
$action = $_SERVER['PHP_SELF'];
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
echo 'Use POST method to pass form values';
echo "$_POST[email]";
}
?>

Email:


If you want to send a form or data to the server in the browser, you can use the GET or POST method. The GET method uses the browser address bar to pass the value when accessing the URL. We can see this kind of URL string on many websites. What is shown in Figure 5-1 is to use the GET method to pass parameters.

                                                                                                                                                                                       Error-prone, and the length of the string passed by GET cannot exceed 250 characters If the characters are too long, the browser will automatically truncate them, resulting in data loss. In addition, the GET method does not support any characters other than ASCII characters. For example, when it contains Chinese characters or other non-ASCII characters, additional encoding operations are required, although sometimes the browser can automatically complete it (you can use the url_encode and url_decode functions, use See section 2.9.2 for details on the method).
When the POST method sends variable data, it is opaque to the user. According to the HTTP protocol, the data is attached to the header information of the header and the user cannot modify it at will. This is much safer for web applications. And using POST, you can send large volumes of data to the web server.
Because POST is sent together with the HTTP header information, when the POST form submission is triggered, if the user clicks the "Back" button while browsing the page, the browser will not automatically resend the POST data. If the user clicks the "Refresh" button at this time, there will be a prompt "The data has expired, do you want to resubmit the form?" This is not as convenient as GET. When using GET to pass values, even if the user uses the "Back" or "Refresh" button, the browser's URL address still exists.
Therefore, we need to flexibly choose GET and POST to submit form data according to the actual application during development.
It is worth mentioning that if the form closing tag is missing in HTML, then the entire form will not trigger any submission action. During actual development, some careless people will find that nothing happens when clicking the button. In fact, just check the form code carefully. Sometimes even if one HTML character is missing, the browser will not do the work for us.
5.4 Form Elements
There are more than a dozen tag elements used in forms. The commonly used and important tags in PHP development are shown in Table 5-1.
Table 5-1
Form element description
input type="checkbox" checkbox, allowing users to select multiple options
input type="file" file browsing box, which can be used to open a modal window when a file is uploaded To select a file
input type="hidden" hidden label, used to implicitly submit variable values ​​​​in the form
input type="password" Password text box, when the user enters characters in the text box, it will be replaced and displayed as * No.
input type="radio" single option, used to set a set of options, the user can only select one
input type="reset" to clear and reset the content of the form, used to clear the content of all text boxes in the form, and Restore the selection menu items to their initial values ​​
input type="submit" form submission button
input type="text" single-line text box
select drop-down list box, which can be single-selected or multi-selected. The default is single selection. If you want to add multiple selection function, add
Among them, the hidden tag is called hidden Or an implicit tag, which will not appear on the page interface that the user browses. When the user fills out the information form and transfers values ​​across pages, this tag can be used to pass some implicit values.
The password text box is used to hide the password. The text entered by the user will be displayed in the text box with *, but the password is not encrypted and is only replaced by *. Please note this.
The attributes of the form are introduced below. They are used to constrain the behavior or display of form elements in the form. Their meanings and constraints are shown in Table 5-2.
Table 5-2
Attribute name description indicates the name of the
name text box. Based on this name, PHP creates a key named name in the super global array.
The width of the size text box. In the select drop-down menu, it means that it can Number of option lines seen
The default value in the value text box. Note that this value cannot be applied to the type=password password text box and type=file file text box.
multiple This attribute is used in the drop-down list menu select to specify the Option users can use Ctrl and Shift keys to make multiple selections
rows The number of character columns that can be accommodated when the multi-line text box is displayed, width
cols The number of character lines that can be accommodated when the multi-line text box is displayed, height
In addition to some of the above necessary attribute elements , there are also some standard attributes, such as class, style, id, etc., you can refer to HTML related information.
In some dynamic scripts, PHP needs to be used to generate form elements from the database according to different requests. Below we will show several methods of generating form buttons or options.
1. Dynamically generate 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);
}
?>
This script will generate a list of radio button groups named city_id, and the default option is 024-"Shenyang" .
2. Dynamically generate multi-option drop-down list menus.
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",
"Movies" => "Movies",
"Internet" => "Internet",
"Travel" => "Travel");
$html = generate_checkboxes("interests",$options, $interests);
?>
Select your interests:




3. Generate a multi-select drop-down list menu.
$options = array(
'1' => 'Please select',
'news' => 'News',
'events' => 'Events',
'publications' = > 'Manuscript'
);
$default = "news"; //Default selected items
$html =generate_muilti_option("select", $options, $default);
echo $html;
function generate_muilti_option ($ name,$options, $default){
//Create a list that allows multiple selections
echo '

The $_SERVER server variables used in this example are The following are the following:
? HTTP_REFERER saves a complete source URL address.
? SERVER_NAME Current server name.
? PHP_SELF The full path of the current script, including the file name.
We can compare through "http:// == ". If they are the same, it is a legal form submission, otherwise it will not be processed. Run the Example 5-2 script and click the "Submit" button. The result is shown in Figure 5-2.

Figure 5-2
5.5.2 A complete form processing
We have already learned about the simple way to process forms. Below we will create a complex form with the code shown below.



   
   


   
   


   
   


   
   


   


    开发语言:
   


   


   
   

姓名:
密码:
年龄:
     
   
自我介绍:


体育爱好:
   

网球
   
足球

篮球

保龄球

     
php

java

perl

c++

.NET

delphi


      开发工具:
   
 


该表单包括了常用表单元素:单行文本框、多行文本框、单选项(radio)、多选项(checkbox),以及多选菜单。Detailed explanation is provided below.
? maxlength is an attribute associated with the password text box, which limits the maximum length of the password entered by the user to 10 characters.
? The age list box is a list menu, and its named attributes have their own values ​​​​for selection. Selected is a specific attribute selection element. If an option is attached with this attribute, the item will be listed as the first item when displayed.
? The content in the intro text box displays the text, row and column width according to rows and cols.
? fave_sport is a group of radio buttons (radio). We need to name the elements according to the group. For example, this group of radio buttons is called fave_sport. The user can only select one, and there is only one value in the sending script.
? Like the single option, all multi-option members must also have attributes with the same name, and brackets [] need to be added to the attribute name, so that the value of the multi-option is sent to PHP in the form of an array. Languages ​​is this form.
? The checked tag refers to a certain value in single option and multi-option, which is selected by default.
The display screen of the above form is shown in Figure 5-3.

Figure 5-3
Because the form form in the HTML above uses the POST method to transfer data, the data submitted by the user will be saved in the super global array of $_POST or $_REQUEST. We use the value in the $_POST array to Submitted data can be processed.
Submit the data in the above form to the someform.php script. The processing logic of the script is as follows:
//By judging whether the variable name of the button is defined in $_POST, if so, it means that the form has been submitted
if (isset($_POST["btn_submit"])){
if (empty($_POST['username'])){
echo "You did not enter a username";
exit(0);
}
if (empty ($_POST['password'])){
echo "You did not enter your password: ";
exit(0);
}
echo "Your username: ".$_POST['user_name']."
" ;
echo "Your password (plain text): ".$_POST['password']."
";
echo "Your age: ".$_POST['age']."< br />";
if (!empty($_POST['languages'])){
                 echo "The language you selected is:"; _POST['languages'] as $lang){
                                                                                                                   echo $lang. DEVELOP_IDE_))) {

Echo "The development tool you use is:";
// The array of the user's multiple choice of the development tool menu
Foreach ($ _post ['Develop_ide'] as $ IDE . "  ";
    }
  } else {
          echo "You have not selected a development tool";
    }
  echo "Your self-introduction: ".nl2br($_POST['intro'])."
";
echo "Web page hidden value (passed through hidden tag value): ".$_POST['from']."
";
}
?>
Instructions: Submit using POST method Forms transmit form data through the header part of the HTTP protocol. Theoretically, there is no upper limit on the size of the data. However, when using PHP for POST submission, the file size is limited by the PHP configuration file (php.ini). We can modify the post_max_size parameter in the php.ini file and change the default 2M bytes to the size we need. However, due to the characteristics of the HTTP protocol, this value should not be set too large, and the maximum is 8M.
5.6 Other methods of processing forms
Now, let’s take a look at two programming methods for processing forms and their advantages and disadvantages.
5.6.1 Use 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 the values ​​​​of $_GET, $_POST, and $_COOKIE. You can also add a prefix to each imported variable.
bool import_request_variables (string types [, string prefix])
The types string in the parameter allows g, p, c characters, or any combination of 3 characters. Among them, "g" represents GET variables, "p" represents POST variables, and "c" represents cookies.
Note: There is a difference in the order of the 3 characters. When "pg" is used, the POST variable will overwrite the $_GET variable with the same name; conversely, when "gp" is used, the $_GET variable array will take precedence over $ _POST.
The prefix parameter is used as the prefix of the variable name and is placed before all variables imported into the global scope.For example, if we have a $_GET super global variable array named "userid" and provide "pref_" as a prefix, then we will get a global variable named $pref_userid. If we want to import other global variables (such as the $_SERVER variable), please consider using the extract() function (introduced in the chapter Functions). Note that when using the prefix, do not conflict with existing data or variable names.
A script example using the import_request_variable() function to implement variable import is as follows:
//Import variable values ​​submitted by POST, with the prefix post_
import_request_variable("p", "post_");
//Import variable values ​​submitted by GET and POST , the prefix is ​​gp_, GET takes precedence over POST
import_request_variable("gp", "gp_");
//Import the variable values ​​​​of Cookie and GET, 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, please 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 imported variable names
echo "Imported using the import_request_variables function Variable value: ".$import_Username;
}
?>

Please enter your name:






This form prompts the user to enter a name. After completion and submission, the script will It is displayed on the browser, as shown in Figure 5-4.

Figure 5-4
Note: The prefix parameter is required. If no prefix is ​​specified, or an empty string is specified as the variable prefix, PHP will throw an E_NOTICE error. The
import_request_variables() function provides us with an intermediate method, which is suitable for the following situations:
1. When the user cannot use the super variable array;
2. When the register_globals parameter of the php.ini configuration file is Off (the default value for versions after PHP 5 is Off), use import_request_variables to import the GET/POST/Cookie super variable arrays into the global scope.
3. During development, as long as the introduced variable scope is declared, there is no need to write $_GET or $_REQUEST and a bunch of long super global array names.
5.6.2 Use the extract() function
We can use the extract() function, such as adding extract($_POST);extract($_GET); at the front of the receiving page script to export several statements for the form The processed super variable array value, 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 normal variables:
// Convert the variables obtained from the $_GET and $_POST super variable arrays It is a normal variable, so you can directly display the variable name
extract($_GET);
extract($_POST);
echo "Hello, $username $age";
?>

Name:
Age:


The interface implemented is shown in Figure 5-5 shown.

5.7 Transferring data between multiple pages
When encountering a very large form, it is impossible to put all the forms on one page. You need to decompose a large form into several small forms and save them on several pages. , when the first form is filled out, the values ​​of the form need to be collected and passed to the next form page.
We can use the following methods to handle it.
? Use hidden elements of the form (hidden).
? Save the data of the current form in SESSION (see the session chapter for details).
? Save the current form data in the MySQL database.
You can choose a solution from the above three options that is easy for program processing and debugging.POST can be used to transfer values ​​in the form, so the size of the data transferred is not a problem. In addition, when debugging the program, we can know whether the current variable is the expected value by viewing the HTML source file.
For a very large form, we have to find a way to break it 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 previousKyoto 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//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 value passed through the URL.
5.7 Transferring data between multiple pages
When encountering a very large form, it is impossible to put all the forms on one page. You need to break the large form into several small forms and save them in several pages. , when the first form is filled out, the values ​​of the form need to be collected and passed to the next form page.
We can use the following methods to handle it.
? Use hidden elements of the form (hidden).
? Save the data of the current form in SESSION (see the session chapter for details).
? Save the current form data in the MySQL database.
You can choose a solution from the above three options that is easy for program processing and debugging. POST can be used to transfer values ​​in the form, so the size of the data transferred is not a problem. In addition, when debugging the program, we can know whether the current variable is the expected value by viewing the HTML source file.
For a very large form, we have to find a way to break it 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 like the above to process the value passed from the previous page or through the URL.
5.9 Form Security
Visitors to the website are very different. He may be a student, a professor, a computer novice who doesn’t understand anything, or more likely a hacker. Whether it is an unexpected error that pops up, or Deliberately looking for trouble, they always like to not input the way we want them to, or look for security holes in our sites.
Some common vulnerabilities in websites are often caused by developers’ carelessness. Of course, some of them are due to operating system or server configuration. Common safety hazards and proportions are shown in Table 5-4.
Table 5-4
Program defect ratio Example
User input not verified 42.60%
Access control defects 3.60%
SESSION ID verification vulnerability 5.40%
Database SQL injection 28.60%

The above introduces the detailed explanation of PHP forms, including aspects of content. I hope it will be helpful to friends who are interested in PHP tutorials.

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