Home > Articles

This chapter is from the book

This chapter is from the book

Program Input

On the Web, input—any data your program needs to process or know in order to perform its task—is gathered from an HTTP request. An HTTP request occurs whenever a user types in an address, clicks a link, or clicks a button on a Web page. The request contains information about the request, such as the desired file, any cookies that have been sent to the browser for that site, and any form fields that are being submitted to the server.

The request can be very complicated, however. Since PHP was created with Web programming in mind, it makes gathering this information less complex.

You still have to know a few things about the HTTP request because PHP divides the input it receives into the categories based on how they arrive in the HTTP request. Input is divided into three main categories: get, post, and cookie variables. You must know which category your variables are in to be able to access them.

NOTE

There is a more direct shortcut for accessing variables discussed later in this chapter, along with its advantages and disadvantages. However, make sure you understand this material before you try to use the shortcut.

For now, don't worry about the cookie variables category; it will be covered in Chapter 17, "Putting It All Together."

Get and Post Form Methods

You may recognize the other two categories, get and post, from your previous HTML experience; they are attributes used in the method tag of a form. Depending on which sort of form you use, you will need to use the corresponding category in PHP.

Get forms are commonly used for search queries and small amounts of information that may be exposed in the address bar of the visitor's browser. A get request is also made whenever a user clicks a link.

CAUTION

You should not use a get form when requesting a visitor's password or other sensitive information. Items from a get form will be in plain sight of anyone within sight of the visitor's monitor.

When information is sent to the server in a get request, PHP puts all of the form fields and their values in the appropriate input array, $HTTP_GET_VARS. So, to get the value of a field, use the value of $HTTP_GET_VARS with the field name as the key.

Let's take a look at an example. The following program generates a personalized greeting for a visitor:

<?php
/* ch03ex10.php – shows personalized greeting form */
?>
<html>
<head><title>Welcome!</title></head>
<body>

<form action="ch03ex11.php">

What's your name? <input type="text" name="userName">
<input type="submit" value="Continue">

</form>

</body>
</html>

Since the form's method isn't specified and get is the default method, get is assumed. The PHP file can then find the value for the field in $HTTP_GET_VARS['name'], as shown in the following file:

<?php
/* ch03ex11.php – shows personalized greeting */
?>
<html>
<head><title>Welcome!<title></head>
<body>

<h4>
Welcome, <?= $HTTP_get_VARS['name'] ?>!
</h4>

</body>
</html>

The username and password are shown to the user just as they were entered on the form.

Now let's take a look at using links to make get requests. When I refer to links, I'm not just referring to the HTML <a> tag. I'm also referring to addresses typed directly into a browser's location bar or the address specified in an <img> tag.

To investigate this further, let's create a single-question survey. The question, which could be inserted anywhere in an HTML file, should be set up similar to this:

<?php
/* ch03ex12.php – survey form */
?>
<html>
<head><title>Survey</title></head>
<body>

Which animal do you like better? 
<a href="ch03ex12.php?answer=dogs">Dogs</a> or
<a href=" ch03ex12.php?answer=cats">Cats</a>

</body>
</html>

Upon clicking one of the links, the visitor is taken to answerSurvey.php, which looks like this:

<?php
/* ch03ex12.php - handles survey answers */
?>
<html>
<head><title>Your Answer</title></head>
<body>

You said you like <?= $HTTP_GET_VARS['answer'] ?> the best!

</body>

As you can see, get requests are handled precisely the same as those made with forms. You can also change the question file so that the answer is collected using a form instead of a link. Try this for practice.

Now that you know about get forms, let's take a look at the other form method. Post forms are used for larger amounts of data (such as detailed user information, e-mail messages, or file uploads) and data that should not be visible in the browser's address bar (such as passwords). An example of data being clearly visible in the browser's Address bar is given in Figure 3.3.

Figure 3.3 Sensitive information in a get request may be revealed in a browser's Address bar.

Let's try a practice problem. Yahoo!, Hotmail, and Excite all offer private services which require a username and password. In order to verify that a user is really the user he claims to be, services such as these must check that the login name and password are valid. For now, we'll just focus on collecting the data. The process of actually verifying the information is a separate concept, which will be discussed at various times later in this book, particularly in Chapter 6, "The if, elseif, and else Statements," and Chapter 13, "Creating Dynamic Content with PHP and a MySQL Database," when we discuss if statements and using databases, respectively.

The program will have two files: one to request the user's username and password and a second to retrieve that data.

The first file will contain a form that has its method set to post. If we don't set the method attribute, the username and password will be left out in the open in the user's address bar, which is considered to be a security risk. Anybody that happens to walk by the visitor's computer can see the password in the browser's Location or Address bar. Figure 3.3, shown previously, shows this vulnerability.

Here's the first file:

<?php
/* ch03ex13.php – login form */
?>
<html>
<head><title>Authorization Required</title></head>
<body>

<form action="ch03ex14.php" method="post">

Username: <input type="text" name="username"><br>
Password: <input type="password" name="password"><br>
<input type="submit" value="Login">

</form>

</body>
</html>

That's not too complicated; it's just an HTML page with a form. Now we need to set up the file to accept the data this form posts. For now, we're going to set up our program to show the visitor the username and password he entered. To do so, we'll use the contents of the $HTTP_POST_VARS array because the information was posted with the post method.

Here's the second file, which handles the data posted from the first file:

<?php
/* ch03ex14.php - shows the visitor what username and password he entered */
?>
<html>
<head><title>Enter your password</title></head>
<body>

Username: <?= $HTTP_POST_VARS['username'] ?><br>
Password: <?= $HTTP_POST_VARS['password'] ?>

</body>
</html>

This should look a lot like the $HTTP_GET_VARS example did; the only difference is that we've changed the method for the form, so we have to change which array we use in PHP—the two (the value of the form's method tag and the name of the script's input variable) must always correspond with one another.

For practice, try modifying this program to use get as the method.

TIP

You'll need to modify both files in order to make it work with the get method.

Once you've modified it and it's working, look at the address in your browser's Address or Location bar after you've posted the form. You should notice a string (such as "?username=joe&password=joepass") appended to the end of the filename. This is another illustration of why get forms and passwords aren't a good mixture.

Using Forms

Although creating HTML forms isn't technically a part of PHP, it is definitely a part of learning PHP. Since forms are just about the only way for your program to collect information from the user, you must use the form elements allowed by HTML to construct the most intuitive form possible.

TIP

The intuitiveness of a form is the overall effectiveness it has for the user. For example, using a single-line text input where the user will probably be entering a large amount of text makes it difficult for the user to read and edit what he's typing. In that case, it would be more effective to use a textarea.

The various form-input types will be discussed to help you create the most intuitive forms, which in turn makes your visitors experience more pleasing.

Form inputs allow the user to enter text and make selections. For example, if you wish to ask a user for his name, a simple text input is fine. The text input follows this syntax:

<input type="text" name="field_name" value="default_value">

The value attribute is optional; in most cases, it would be left blank. However, if you wish to suggest a value for the user's input, you can include the value="default_value" attribute and the value will appear in the field.

For example, to suggest a default value using a variable you already have (such as one that was entered from a previous form), you can specify the value attribute by outputting the variable's value with short equals tags, like so:

<?php
/* ch03ex16.php – default value example */

// Assume $user_name can come from a previous form submission;
// it's specified here for clarity.
$user_name = "John Doe";

// Print a form using this name as the default value for the user_name field
?>

<form>
<b>Name:</b> <input type="text" name="user_name" value="<?= $user_name ?>"><br>
<input type="submit">
</form>

NOTE

Assuming PHP has its default configuration, you should be able to set the action attribute of this form to the name of the program file (such as ch03ex16.php) and the value of the field would be updated as the default value every time the submit button is clicked.

This example is primarily here to demonstrate that you can specify a dynamic default value, just as any other output can be dynamic.

There are several types of inputs for making selections. We'll look at radio and check box inputs first, then compare them to select inputs.

The radio input is used to ask the user to pick one item out of a list. The syntax follows this form:

<input type="radio" name="field_name" value="field_value">

In this case, the value attribute is not optional; if you don't specify it, the field will appear to be blank from within PHP, even if the option is selected. This type of input is best used in groups; the following example could be used to ask a visitor what his favorite pet is

What's your favorite pet?<br>
<input type="radio" name="favorite_pet" value="dog">Dog<br>
<input type="radio" name="favorite_pet" value="cat">Cat<br>
<input type="radio" name="favorite_pet" value="camel">Camel<br>
<input type="radio" name="favorite_pet" value="none">None<br>

Notice that all of the inputs have the same name; this is a feature of the radio input that allows the user to choose only one option, but it only works if the radio buttons all use the same name.

If you wish to get multiple answers from a user, you would need to use a check box input, which follows this syntax:

<input type="checkbox" name="field_name" value="field_value" checked>

Again, the value attribute must be included with this input. However, the checked attribute you see at the end of the tag is optional; if it's included, the check box will appear checked by default.

This type of input is commonly seen when you sign up for newsletters and free services online. These services gather information about the users they have so they can charge their advertisers more for targeted advertising. The following example demonstrates the common question, "What magazines do you subscribe to?"

What magazines are you currently subscribed to?<br>
<input type="checkbox" name="us_news" value="true">US News
<input type="checkbox" name="sports_illustrated" value="true">Sports Illustrated
<input type="checkbox" name="national_geographic" value="true">National Geographic
<input type="checkbox" name="time" value="true">Time

Notice that all of the name attributes are different; they cannot be the same or multiple selections would overwrite each other and only the last one would be retrievable from within PHP.

The select field allows similar data collection, using a smaller space. For example, listing all of the countries for the user to pick one could take up a lot of space on your form, making it seem longer than it really is. By putting all of the countries into one select input, the long list is compressed into one line. The syntax for a select input is

<select name="field_name" size="field_height" multiple>
 <option value="option_value">option_text</option>
 ...
 <option value="option_value">option_text</option>
</select>

The value attribute is optional; if it is omitted, the text used for option_text will be used as the value as well (but option_text never overwrites a value specified in option_value). The multiple attribute is also optional; leaving it out forces the user to pick only one option. If specified, the size attribute determines how many options are visible at once. If the size is omitted, the input appears as a drop-down list; otherwise (if it is specified), the list appears in a scroll box.

Here's a very short example that could be used to ask a user what country he is from:

What country do you live in?
<select name="country">
 <option>China</option>
 <option>France</option>
 <option>Germany</option>
 <option>United Kingdom</option>
 <option>United States</option>
</select>

Notice that the multiple attribute wasn't included because you only want to allow the user to pick one country. Also, the value attributes were omitted because the text found between the two option tags is all you need to know. (The value tags are often used to associate numeric codes that the program understands with textual names that the visitor understands.)

It's not always appropriate to limit the user to just one selection. To allow multiple selections, the multiple attribute must be specified. Once it is, the user can make multiple selections using Ctrl and Shift. The following input asks the user about his hobbies:

What are your hobbies?<br>
<select name="hobbies[]" multiple>
 <option>Travel/Sightseeing</option>
 <option>Automotive/Cars/Hotrods
 <option>Sports/Fitness</option>
 <option>Reading</option>
 <option>Outdoors/Camping/Fishing</option>
</select>

This input allows the user to select from zero to all of the options given.

CAUTION

Notice the brackets in the name attribute; since they are present, the hobbies variable in PHP will be an array, with each element being an element selected from the options list. If the brackets were left out, only the last option selected would be visible within PHP.

Let's say Automotive and Reading are the two options chosen from this list, and the form is submitted. In this case, the $hobbies array contains

Array(
 [0] => "Automotive",
 [1] => "Reading" )

The last method for gathering information is the textarea. The textarea is used to allow the user to type a large amount of text, such as a feedback message. Here is the basic syntax for a textarea field:

<textarea name="field_name" rows="field_height" 
cols="field_width">default_value</textarea>

Although the rows and cols attributes are optional, it's best to specify them. You need to experiment a little with these to get a feel for how they affect the size of the textarea. The default_value shown between the beginning and ending tags shows where you can suggest a default value for the textarea to contain. Because the textarea allows for multiple paragraphs, adding a value attribute is not appropriate; this is why the default value is specified between the textarea's opening and closing tags. If you chose to omit the default value, you still need to include the closing </textarea> tag.

There are two inputs to submit a form: submit and image. These inputs work about the same way, except the latter uses an image instead of a gray button.

Here's an example of each; these two uses are functionally equivalent:

<input type="submit" value="Submit">
<input type="image" src="/path/to/image.gif">

Your forms must always include a submit button or the form won't be very effective. Pressing Enter or using JavaScript works most of the time, but it's always preferable to have a button for those who can't use Enter or don't support JavaScript.

You might want to use this section as reference until you get used to creating forms (if you're not already used to it). With some practice, you'll have no trouble at all creating intuitive forms.

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