Use HTML forms in combination with PHP

Source: Internet
Author: User
The ability to easily operate information submitted by users through HTML forms has always been one of the advantages of PHP. In fact, PHP version 4.1 adds several new methods to access this information and effectively removes the most commonly used methods in previous versions. This article studies different methods of submitting information using HTML forms, and uses earlier PHP versions and newer versions. This article begins with studying a single value, and then builds a page that can access any available form value in general.

Note:This document assumes that you have access to a Web server running PHP version 3.0 or later. You need to have a basic understanding of PHP and HTML forms.

HTML form

When reading this article, you will see how different types of HTML form elements provide PHP accessible information. For this example, I used a simple information form consisting of two text fields, two check boxes, and one option box that allows multiple numbers:

Listing 1. HTML form

<HTML> 

If no method is specified, the form uses the default method.Get, The browser uses it to append the form value to the URL, as shown below:

Http://www.vanguardreport.com/formaction.php? Ship = midnight + runner & tripdate = 12-15-2433 & authentication = Yes & crew = snertal & crew = gosny

Figure 1 shows the form itself.

Figure 1. HTML form



Back to Top

Old method: Access global variables

TheCodeProcess the form value as a global variable:

Listing 2. Form values as global variables

<? PHP echo "ship = ". $ ship; echo "<br/>"; echo "tripdate = ". $ tripdate; echo "<br/>"; echo "comment = ". $ annotation; echo "<br/>"; echo "Contact = ". $ contact;?>

The submitted value is displayed on the generated web page:

Ship = midnight runner tripdate = 12-15-2433 condition ation = Yes contact =

(As you will see later, there is no contact value because the box is not selected ).

The representation in Listing 2 is of course convenient, but it is only applicable to PhP pseudoinstructions.Register_globalsSetOn. Before Version 4.2, this was the default setting, and many PHP developers did not even realize this problem. However, since version 4.2,Register_globalsIsOffIn this case, the representation does not work properly because the variable is no longer created and initialized with the appropriate value.

However, you can use other methods to initialize these variables. The first method is to changeRegister_globals. Many developers who use shared servers do not have the right to change the value for the entire server, but can change the behavior for a specific site. If you have. HtaccessFile Access, you can enable by adding the following pseudoinstructionsRegister_globals:

Php_flag register_globals on

Given the uncertainty about the availability of this feature, it is recommended that developers do not use or rely on this method to obtain variables. So what options do you have?

If your system is running version 4.1 or later, another option is to useImport_request_variables ()Register a set of global variables selectively. You can use this function to import get, post, and cookie values. You can also add a prefix for each item if you want. For example:

<? PHP import_request_variables (GP, "formval _"); echo "ship = ". $ formval_ship; echo "<br/>"; echo "tripdate = ". $ formval_tripdate; echo "<br/>"; echo "comment = ". $ formval_authentication ation; echo "<br/>"; echo "Contact = ". $ formval_contact;?>

Here, get and post values are imported-UseCTo import the cookie value.PFollowGSo the post value will overwrite the get value of the same name.

However, if you are like many developersNoWhat should I do if I run version 4.1 or later?



Back to Top

Set of access form values

For those who run earlier versions or do not want to use global variables, you can choose to use$ Http_get_varsAnd$ Http_post_varsArray. Although they are not in favor of using these sets, they are still available and widely used. When they are no longer used$ _ GetAnd$ _ PostArray to replace them.

The two types of arrays are hash tables ).HashIt is an array that creates an index by using a string value instead of an integer. When using a form, you can use the value name to access the value, as shown in listing 3:

Listing 3. Accessing form values through a hash

<? $ Ship_value = $ http_get_vars ['ship ']; echo $ ship_value; echo "<br/>"; $ tripdate_value = $ http_get_vars ['tripdate']; echo $ tripdate_value; echo "<br/>"; $ configuration_value = $ http_get_vars ['configuration']; echo $ configuration_value; echo "<br/> "; $ contact_value = $ http_get_vars ['contact']; echo $ contact_value;?>

By using this method, you can retrieve the values of each field by name.



Back to Top

Single name, multi-value

So far, each name has only one value. What if there are multiple values? For example, the crew species list box allows multiple values to be submitted with the name crew.

Ideally, you want to use these values as arrays so that they can be retrieved explicitly. To achieve this, you must slightly modify the HTML page. Fields to be submitted as arrays should be named in square brackets, as shown in figureCrew []Medium:

Listing 4. Modifying the HTML page

... <TD> <select name = "crew []" multiple = "multiple"> <option value = "xebrax"> xebrax </option> <option value = "snertal"> snertal </option> <option value = "gosny"> gosny </option> </SELECT> </TD>...

Once you make the changes, retrieving the form value actually generates an array:

Listing 5. Accessing variables as Arrays

... $ Crew_values = $ http_get_vars ['crew']; echo "0 )". $ crew_values [0]; echo "<br/>"; echo "1 )". $ crew_values [1]; echo "<br/>"; echo "2 )". $ crew_values [2];...

Now, multiple values are displayed after the page is submitted:

0) snertal 1) gosny 2)

Note that this is an array whose subscript starts from 0. The first encountered value is in position 0, the next value is in position 1, and so on. In this example, I submitted only two values, so the third item is empty.

Generally, you do not know how many items will be submitted, so you can use the fact that it is an arraySizeof ()Function to determine the number of submitted values without directly calling each item:

Listing 6. Determine the array size

... For ($ I = 0; $ I <sizeof ($ crew_values); $ I ++) {echo $ crew_values [$ I]; echo "<br/> ";}...

However, sometimes the problem is not that there are too many values, but that there is no value at all.



Back to Top

Surprisingly disappearing check box

The check box is submitted only when it is selected. This is important. Otherwise, its disappearance will tell you the truth you need to know: the user does not click the check box. You can useIsset ()Explicitly check whether the value is set:

Listing 7. Check whether the check box is submitted

... $ Contact_value = $ http_get_vars ['contact']; echo $ contact_value; If (isset ($ contact_value )) {// the checkbox was clicked} else {// the checkbox wasn't clicked }...


Back to Top

Get all form values

The check box field is just one example of a situation where you may not be completely confident about the expected form value name. Generally, you will find a common method to access all form values is very useful.

Fortunately, because$ Http_get_varsAnd its similar type are only scattered lists, you can use some features of the array to operate on them. For example, you can useArray_keys ()Function to obtain the list of all potential values:

Listing 8. retrieving the list of form value names

... $ Form_fields = array_keys ($ http_get_vars); For ($ I = 0; $ I <sizeof ($ form_fields); $ I ++) {$ thisfield = $ form_fields [$ I]; $ thisvalue = $ http_get_vars [$ thisfield]; echo $ thisfield. "= ". $ thisvalue; echo "<br/> ";}...

In this example, you actually combine several technologies. First, retrieve the form field name array and name it$ Form_fields.$ Form_fieldsAn array is a typical array, so you can useSizeof ()Function to determine the number of potential keys and traverse each item cyclically. For each item, retrieve the field name and use the name to obtain the actual value. The generated web page looks as follows:

Ship = midnight runner tripdate = 12-15-2433 authentication = Yes crew = Array

There are two important issues here. First, the contact field has no return value at all, as expected. Second, the crew value (by the way, you may know that its name is crew ratherCrew []) Is an array rather than a value. To retrieve all values, you must useIs_array ()The function detects all arrays and processes them accordingly:

Listing 9. Handling Arrays

... For ($ I = 0; $ I <sizeof ($ form_fields); $ I ++) {$ thisfield = $ form_fields [$ I]; $ thisvalue = $ http_get_vars [$ thisfield]; If (is_array ($ thisvalue) {for ($ J = 0; $ j <sizeof ($ thisvalue); $ J ++) {echo $ thisfield. "= ". $ thisvalue [$ J]; echo "<br/>" ;}} else {echo $ thisfield. "= ". $ thisvalue;} echo "<br/> ";}...

The result is all submitted data:

Ship = midnight runner tripdate = 12-15-2433 authentication = Yes crew = snertal crew = gosny


Back to Top

Last Note: Point

Since you have a form operation page that can adapt to your submission of any form value, you need to take a moment to consider a frequently used PHPProgramStaff were surprised.

In some cases, the designer selects a graphic button instead of a submit button. The graphic button is shown in figure 2 and the code is shown in listing 10.

Listing 10. Add a graphic button

... <Tr> <TD valign = "TOP"> crew species: </TD> <select name = "crew []" multiple = "multiple"> <option value = "xebrax"> xebrax </option> <option value =" snertal "> snertal </option> <option value =" gosny "> gosny </option> </SELECT> </TD> </tr> <TD colspan = "2" align = "center"> <input type = "image" src = "button.gif" name = "formbutton"/> </TD> </tr> </table>...

Figure 2. graphical buttons on the form

Note that although there is only one image, there are two graphical buttons (or expected results ). As a developer, you can check the X and Y coordinates returned together with the value to know where the user clicked. In fact, submitting the form as is may create a URL and a query string ending with the following:

... Snertal & crew % 5B % 5d = gosny & formbutton. x = 37 & formbutton. Y = 14

Note that. X and. y are appended to the button name. However, if you want to submit the page and view the result, you will see:

Ship = midnight runner tripdate = 12-15-2433 authentication = Yes crew = snertal crew = gosny formbutton_x = 37 formbutton_y = 14

note that the period (.) has been converted to an underscore (_). This seems a bit strange, but it is necessary because the variable name in PHP cannot have a number, so $ formbutton. x is an invalid variable name. In fact, any dot in the form name-not just for image buttons-is converted into underscores.

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.