Forms are used to get information from users. HTML contains tags that allow you to create forms, and the Hypertext Transfer Protocol (HTTP) has features that place information obtained from forms into specified variables, for use by PHP programs. Generally, a PHP program will process the form information, perhaps save some of the information in a file, and then output something to the user (e.g., in the simplest case, "Your information was received").
Forms are useful because permit the creator to specify particular items he or she wants from a visitor to the web site, and, in some cases, to limit the possible responses of visitors. For example, if you are trying to determine which state a particular visitor to your web site is from, it would be useful to be able to limit the user to one name for each state: For example, if asked, different visitors might specify "MA" or "Ma" or "Mass" or "Massachusetts," or even "the Bay State" for Massachusetts. If, however, you limit the visitor's choices to post-office abbreviations (e.g., "MA," "ME"), it will make it easier for you to process the information.
In HTML, a form is surrounded by the tags <form> and </form>. The first tag (<form>) also contains information regarding what is to be done with the information obtained in the form. For example, the tag might look something like this:
<form method="post" action="dosomething.php"> </form> |
The preceding form tag specifies that the form uses "post" (the most common protocol for passing information received in a form to PHP), and that the PHP program to which the data should be passed is called dosomething.php.
Also, each place in the form where data is requested has an <input> tag, which specifies the type of object to show the visitor, and the name of the variable to which the input is assigned. Here is an example of input tags:
<form method="post" action="dosomething.php"> <form method="post" action=""> |
The preceding text field and button are displayed as follows:
Once the form is submitted (by pressing the button), the PHP program dosomething.php is run, and the variable $firstname will then contain whatever text the visitor entered in the box. Note that the PHP variable name is preceded with a dollar sign ($), while the HTML variable name is not.
Common types of form inputs include the following:
Fortunately, web-authoring software such as Dreamweaver provides a user interface that allows you to create a form in an intuitive, WYSIWYG manner. Dreamweaver takes care of the HTML code for you. Click here for more information about how to use Dreamweaver to create forms.
Once data is collected in a form, and passed to a PHP program, the PHP program can manipulate, store, and output the data just as it would any other variable. Click here for an example.