Home > Articles

PHP Basics

This chapter is from the book

3.9 Working with Forms

Up to now, you have seen how to write simple PHP applications. However, for building interactive Web sites it is necessary to allow the user to insert data into so-called forms. The content of such forms can be transmitted to the server and a PHP script can react based on the data sent to it. Interacting with a Web server can be done with two methods called GET and POST.

3.9.1 GET and POST

The methods GET and POST are described in RFC2068, which is longer than 160 pages. In this section you learn about the main ideas behind GET and POST, and you learn to use these two methods efficiently.

3.9.1.1 GET

GET is the standard request method for retrieving data from a Web server. When calling a Web site, GET is used to get the document you have selected. Normally calls like that don't have side effects, and that is what GET should be used for. Browsers assume that GET has no side effects and if the page is not in the browser's cache any more, the page will be retrieved again. However, if the original request was via POST, the user would receive a message that the document is no longer in the cache (in section "Building Forms" in this chapter, you will learn to get around this problem).

3.9.1.2 POST

POST is the standard method for submitting data stored in a form to Web server. In the case of POST, the request always contains a body where the information related to the request is stored. This information is coded like a query string. Normally Web developers use POST even when no data on the server is modified.

3.9.2 Building Forms

After you have seen which methods can be used to retrieve data from a Web server, you have a look at a simple form that can be used to send text to a PHP file:

<html>
<body>
    A Simple Form
    <br><br>
    <form action="reaction.php" method="POST">
        <input type="text" name="field_1" size="10"><br><br>
        <input type="submit" name="submitbutton">
    </form>
</body>
</html>

In line number 5 a form is defined. When the user clicks on the Submit button, the data will be sent to reaction.php. The form consists of two components. The first component is a text field called field_1. The second component is the button to submit the form. The end of the form is marked by </form>.

Let's start the script and see what the browser displays (see Figure 3.3).

Figure 3.3Figure 3.3 A simple form.

If you click the button, reaction.php will be started:

<?php
    if   ($field_1)
    {
        echo "field_1: $field_1";
    }
    else
    {
        echo "nothing has been passed to this script";
    }
?>

The first thing done by the script is to see if $field_1 is defined. If the user has inserted data into the form, the variable will be defined in PHP automatically. In contrast to Perl, PHP programmers do not have to extract the variables from the query string themselves because everything is done by PHP.

If $field_1 is defined, the content of the variable will be displayed on the screen.

As you can see, retrieving data from a form is an easy task. In the next step you will see how more complex forms can be built with the help of HTML:

<html>
<body>
    A more complex form
    <br><br>
    <form action="reaction.php" method="POST">
        <input type="text" name="field_1" size="10"><br><hr>
 
        <input type="checkbox" name="box_1">
            display time<br><hr>
 
        <input type="radio" name="myradio" value=1>Value 1<br>
        <input type="radio" name="myradio" value=2>Value 2<br>
        <input type="radio" name="myradio" value=2>Value 3<br><hr>
 
        <input type="password" name="passwd">
            Enter passwords here<br><hr>
 
        <input type="file" name="filename">
            enter the filename<br><hr>
 
        <input type="reset" name="resetbutton">
        <input type="submit" name="submitbutton">
    </form>
</body>
</html>

The first component defined in the form is a text field again. The length of the field is set to 10. In addition to the size of the field, it would also be possible to define the maximum length of the text the user is allowed to insert. This can be done by using maxlength. After defining the text field, a check box is defined. The name is set to box_1. After that you can see how radio buttons can be added to a HTML document. In the example you can see that myradio consists of three components. Only one of those three components can be activated. Depending on which of the three buttons is checked, the appropriate value is sent to reaction.php. If you need fields for inserting passwords, password will be the right type for you. While typing, the user will only see asterisks, so nobody can grab the user's password.

To select a file on the user's hard disk, the type called file can be used. File will create a text box and a button you can click if you need a window where you can select the file using a graphical interface.

Finally, the Submit button is added to the screen. Figure 3.4 shows what comes out when you execute the script.

Figure 3.4Figure 3.4 A more complex form.

If you click on the Submit button, the data inserted into the form will be sent to reaction.php:

<?php
    echo "field_1: $field_1<br>";
    echo "myradio: $myradio<br>";
    echo "passwd: $passwd<br>";
    echo "filename: $filename<br>";
?>

The script displays the values on the screen:

field_1: 23
myradio: 2
passwd: a password
filename: /home/hs/boot.img

Keep in mind that the values in the listing show what you have inserted into the form. The gist of the example is that the information from every field in the HTML form will be stored in a variable after being submitted to a PHP file.

Sometimes it is necessary to give the user the opportunity to select more than just one value in a list. Therefore HTML offers a simple solution using select and option:

<html>
<body>
    Select:
    <br><br>
    <form action="reaction.php" method="POST">
        <select name="fruits[]" multiple size=4>
            <option value="Orange">Orange
            <option value="Banana">Banana
            <option value="Apple">Apple
            <option value="Pineapple">Pineapple
            <option value="Strawberry">Strawberry
            <option value="Cherry">Cherry
            <option value="Coconut">Coconut
        </select><br><br>
 
        <input type="submit" name="submitbutton">
    </form>
</body>
</html>

Now the user can choose some of the fruits presented in the list. Because more than one fruit can be selected, the data structure used by PHP must be an array. In our example this array is called fruits[]. After submitting the content of the form, the array will contain all values the user has selected. To display the content of the array, a simple function can be used:

<?php
    foreach ($fruits as $var)
    {
        echo "$var<br>";
    }
?>

The fruits will be listed one after the other.

3.9.3 Passing Parameters to a Script

In many cases it is useful to call a script and pass some parameters to it. Techniques like that are often needed for banners because the person who has paid for the banner wants to know where a click comes from. For that purpose, parameters are passed to a script that contains information on whose Web site contained the banner.

Let's have a look at a very simple script that does nothing except display two variables.

<?php
    echo "a: $a<br>\n";
    echo "b: $b\n";
?>

The target is to pass parameters to that script via an URL:

http://localhost/test/script.php?a=234&b=197

The script named script.php located in a directory named test on the local Web server is called with the parameter a=237 and b=197. The names of the script and the parameters are separated using a question mark (?). The list of parameters is separated using ampersands (&).

When executing script.php, the result will be displayed by the browser:

a: 234 
b: 197

You have already seen that question marks and ampersands are used as delimiters. What happens if you want to pass one of these signs to the script? Does the Web server get confused because it has to find out which symbols are used as delimiters of which ones are parts of a string? The answer is yes. All "special" characters have to be escaped so that the Web server can parse the URL easily. Luckily PHP provides a function called urlencode, which takes care of things like that. Let's write a small script that generates a list of URLs:

<?php
    echo "<html><body>\n";
 
    $messages[0] = "Pat and Shelley";
    $messages[1] = "Pat & Shelley";
    $messages[2] = "Pat & Shelley!";
    $messages[3] = "Are you sure?";
    $messages[4] = "Hans-Jürgen Schönig";
 
    foreach ($messages as $var)
    {
        echo '<a href="script.php?a='.urlencode($var).
            '"> '.$var."</a><br>\n";
    }
 
    echo '</body></html>';
?>

After displaying some HTML code, five strings are defined and assigned to an array called $messages. Each of the strings contains certain characters that have to be escaped by PHP.

In the next step, links are generated using urlencode. Let's call PHP from the command line and see what the HTML code generated by the script looks like:

[hs@athlon test]$ php genurl.php
X-Powered-By: PHP/4.0.4pl1
Content-type: text/html
 
<html><body>
<a href="script.php?a=Pat+and+Shelley"> Pat and Shelley</a><br>
<a href="script.php?a=Pat+%26+Shelley"> Pat & Shelley</a><br>
<a href="script.php?a=Pat+%26+Shelley%21"> Pat & Shelley!</a><br>
<a href="script.php?a=Are+you+sure%3F"> Are you sure?</a><br>
<a href="script.php?a=Hans-J%FCrgen+Sch%F6nig"> Hans-Jürgen Schönig</a><br>
</body></html>

As you can see, all characters have been escaped. When executing the script using a Web browser, the strings in the array are displayed as links:

Pat and Shelley
Pat & Shelley
Pat & Shelley!
Are you sure?
Hans-Jürgen Schönig

If you click on the first link, script.php will be called:

a: Pat and Shelley
b: 

The text is displayed on the screen. Because no parameters for $b have been passed to the script, the field is empty.

3.9.4 Working with Hidden Fields

Sometimes it is necessary to pass parameters to a script that should not be seen by the user. In HTML it is possible to use hidden fields. The difference between "ordinary" fields and hidden fields is that hidden fields are not displayed by the browser. Therefore parameters can easily be passed from one script to another without giving the user the opportunity to modify the information stored in a hidden field.

Let's assume that you want to write a script that displays the time the previous script has been created:

<?php
    $curtime = localtime();
    $timestr = strftime("%Y %b %d: %T %Z");
    echo "timestr: $timestr<br>\n";
 
    echo '
        <html>
        <body>
            Hello World
            <form action="reaction.php" method="POST">
            <input type="hidden" value="'.$timestr.
                '" name="gentime">
            <input type="submit" name="submitbutton">
        </form>
        </body>
        </html>
    ';
?>

The first script generates the current time and stores it in $timestr. Now a form is generated and the value $timestr is used as the default value of the field called gentime. The only two things that are displayed on the screen are the content of $timestr, Hello World, and a button to submit the information. Reaction.php is called when the user hits the button. Let's have a look at reaction.php:

<?php
    echo "gentime: $gentime";
?>

The content of $gentime is displayed on the screen:

gentime: 2001 Nov 01: 12:31:57 CET

The previous script has been generated at the time listed in the output of reaction.php. Sometimes it is useful to pass the time when the first HTML was generated to all files because this way it is possible to find out when a user has entered the page.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020