Home > Articles

Program Input and Output

In this sample chapter, author Toby Butzon disusses the purpose of input and output, revisits output and introduces advanced types, and examines requesting input and input methods.
This sample chapter is excerpted from PHP By Example, by Toby Butzon.
This chapter is from the book

This chapter is from the book

Without input and output, your program might as well be a regular HTML page. When you add input and output, however, your program's potential will be unlimited. You will be able to collect information from your visitors, ask them questions, and give them a personalized experience that you never could have provided before.

This chapter teaches you the following:

  • The purpose of input and output
  • Output as you've already seen it
  • Advanced types of output
  • Requesting input
  • Input methods

Revisiting Output

Output is the text or information that is sent from your program to the user (specifically, the visitor to your Web site). Think of output as anything the user receives from a program.

For example, when you use a search engine, a program performs the search and sends back HTML data that looks to your browser like any other HTML page. The page isn't like other HTML files—it isn't saved anywhere on the server. The program simply sent its output—a customized HTML page—straight to your browser.

Figure 3.1 illustrates the interaction that might occur between your browser and a server when performing such a search.

Figure 3.1 At its most basic level, the interaction between a visitor's browser and your program works like this: A request is sent to the program and the program's output is its response to the browser.

We've already briefly visited one way of sending output—the echo command. Output can be sent in several different ways. The method that you use depends on the context within the program. The following considerations may influence your decision on which method to use:

  • The content may vary from one visitor to the next, or it may always be the same.

  • The length of the content you wish to send as output might be short (one line or a single word), or it could be long (a paragraph, a table, or even a whole file).

The following sections will help you understand when and how to use each method of output.

The echo Command

You should decide which method to use to send output based on what you're sending. You must decide whether the content is static or dynamic. On top of that, if the content is dynamic, you will have to consider how much of it there is to send.

All output can be divided into two main categories: static and dynamic. Static output is output that will not change from visitor to visitor; it is hard-coded within the file and independent of any variables. Dynamic output, on the other hand, is any output that contains variables, may change from visitor to visitor, or depends upon variables in any way.

To help clarify the division, think of it this way: Static output will never change unless someone changes the program itself; dynamic output will change from user to user, from one time to the next, or depending on an outside data source such as a database. Figure 3.2 illustrates this visually.

Figure 3.2 The left side of this diagram shows the interaction between multiple visitors and a program that produces static output; the right side shows multiple visitors interacting with a program that produces dynamic output.

The echo command is an excellent choice for dynamic content. It allows you to output numbers, text, and variables all in one string. While it can be used for static content as well, your HTML code will become less readable if you have to "wrap" it with PHP code (such as enclosing it in quotes). Therefore, echo should only be used to insert small amounts of dynamic content at a time.

The following example demonstrates a PHP program with nothing but static output—it is returned just as a regular HTML file would be

<html>
<head><title>Example Page</title></head>
<body>This is an example!</body>
</html>

Since none of this code is enclosed in PHP tags, every line is sent as output. Also, the output doesn't rely in any way on any variables or data sources, so it is classified as static.

NOTE

Recall from Chapter 1, "Welcome to PHP," that anything outside of PHP tags is sent straight to output without being processed in any way. Even if a variable is inserted into this code, it would not be interpreted as a variable; rather, the text would be sent just as it appeared.

The following program sends the same result (also static output), but this time uses echo:

<?php
/* ch03ex01.php – demonstrates static output with echo */

echo "<html>\n";
echo "<head><title>Example Page</title></head>\n";
echo "<body>This is an example!</body>\n";
echo "</html>\n";

?>

NOTE

The \n is interpreted as a symbol (called an escape sequence); it means newline and is sometimes also called the newline character. It is comparable to pressing Enter on your keyboard. Without the newlines, all of the outputted HTML code for the previous example would appear on a single line because echo alone doesn't add anything to separate the lines.

This example uses echo in a way that is understandable to PHP but more complicated than most people prefer to read. Look at the first example and then again at the second; in this case, there's no good reason to add all of the extra echo commands, quotes, and newline characters.

Also, according to our basic classification of echo, it should only be used for short, dynamic output. Since this output is long and static, it would be better to stick with the method used in the first example by placing the text outside of the PHP tags.

Now let's take a look at a more appropriate use of echo. The following example is a mostly static HTML page with a small portion of dynamic content—therefore, a small section of PHP code and an echo statement are inserted to output the contents of a variable ($aVariable):

<?php
/* ch03ex02.php – demonstrates dynamic output with echo */

$aVariable = "This is a variable!";

?>
<html>
<head><title>Example: Static vs. Dynamic Output</title></head>
<body>

<b>Static output:</b><br>
The following is static output. It will never change.<br>
Here's a variable: $aVariable<br><br>

<b>Dynamic output:</b><br>
The following is dynamic output. It may change.<br>
<?php

echo "Here's a variable: $aVariable";

?>

</body>
</html>

Here's the output:

<html>
<head><title>Example: Static vs. Dynamic Output</title></head>
<body>

<b>Static output:</b>
This is static output. It will never change.<br>
Here's a variable: $aVariable<br><br>

Dynamic output:<br>
This is dynamic output. It may change.<br>
Here's a variable: This is a variable!

</body>
</html>

NOTE

This output is the HTML code you would see if you used your browser's View Source feature.

The only text the user would actually see in his browser would be

Static output:
This is static output. It will never change.
Here's a variable: $aVariable

Dynamic output:
This is dynamic output. It may change.
Here's a variable: This is a variable!

From the previous example you should recall that PHP doesn't interpret text placed outside of the PHP tags at all. So, the text "$aVariable" was output just as it appeared in the code when it was outside of the PHP tags. However, when it was mentioned inside the tags in a double-quoted string it was interpreted as a variable and the value of that variable was output instead of the actual text "$aVariable."

This is a more appropriate use of echo; notice that only a single line (the one with the variable) was sent with echo. The rest of the output was sent as static output. It will never change and therefore doesn't need echo.

CAUTION

If the strings following echo in the previous example had been single quoted, they would not have been interpreted, and the static output and dynamic output would look the same.

Using Here-doc

So far you've seen output sent by placing it outside of the PHP tags and output sent using one-line echo statements. Now lets take a look at ways to send large amounts of dynamic output without the tediousness and confusion of using multiple echo statements. This is important: In the future, you might find yourself writing programs in which more than 75% of the program is dynamic output.

There are two ways to send large amounts of dynamic output: Use a single echo statement, thereby reducing the clutter of outputting multiple lines of data with echo, or use static output and insert PHP tags to print variables wherever necessary.

The first method is called here-doc (short for "here-document"). Here-doc helps you, the programmer, create clearer multiline strings; it behaves just as a double-quoted string would, but in a more readable fashion. It also allows you to use only one echo statement, as opposed to the clutter of repeated echo statements.

PHP understands and executes the following code, but because the string might not end for many lines and because any double quotes within the string must be escaped, the purpose and contents of the string can become unclear:

<?php
/* ch03ex03.php – demonstrates multi-line double-quoted string */

// Multi-line double-quoted string
echo "<html>
<head><title>Example</title></head>
<body>
This is an example!
</body>
</html>";

?>

Here-doc allows the code to use more understandable multiline strings. First, by using here-doc, you're saying, "Heads up! I'm using a multiline string here." If you take a look at the double-quoted string shown previously, that's not suggested in any way; in fact, if you saw the following line alone, you would think that it was erroneous:

echo "<html>

Using double quotes to create multiline strings is hard to understand just for this reason. There's nothing to say that the string is multiline other than the fact that it isn't ended with a double quote. You or someone reading your code might find themselves asking, "Did he mean to do that?"

There's another reason that here-doc is better than double quotes. Whereas, the double quote at the end of a multiline string doesn't mean much to anybody except "this is the end of a string," here-doc allows you to specify an end identifier that can be descriptive of the string's purpose or contents.

Here's an example of a here-doc statement:

<?php
/* ch03ex04.php – demonstrates use of here-doc */

// Set $user and $pass variables
$user = "John Doe";
$pass = "doe123";

// Outputting a multi-line here-doc string
echo <<<END_USER_INFO
Username: $user<br>
Password: $pass
END_USER_INFO;

?>

The <<< syntax is used exclusively for here-doc. The first line might be read: "echo everything until END_USER_INFO is reached."

NOTE

END_USER_INFO just happens to be the end identifier I chose; while it is appropriate for its descriptiveness of the string, it could have been any other string following the end identifier naming convention, which follows.

Like constants and variables, end identifiers for here-doc strings follow a naming convention. Typically, they are uppercase strings with any multiple words separated by underscores. The convention itself dictates that identifiers can be any combination of letters (upper- and lowercase), numbers, and underscores. However, an end identifier should not contain spaces or begin with a number.

Notice that here-doc strings are interpreted just as double-quoted strings are: Variables are replaced with their values and escape sequences (such as \n) still work.

NOTE

Double quotes in here-doc strings can be escaped, but it isn't necessary as it is in a double-quoted string.

You must place the ending identifier for a here-doc string at the very beginning of a new line. This makes here-doc strings more efficient for PHP to interpret because PHP only has to look for the end identifier at each new line as opposed to every position of every line. However, if you forget to place the end identifier at the leftmost position on a line, you will find yourself trying to figure out an error message for a line that seems to have nothing wrong with it; in fact, it probably doesn't. Make sure any here-doc statements before it are terminated correctly. Remembering this can save you much frustration.

Take a look at the following code, which directly compares the use of a double-quoted string to a here-doc string:

<?php
/* ch03ex05.php – compares use of double-quoted string to here-doc */

// Multi-line double-quoted string
echo "<body bgcolor=\"#FFFFFF\" text=\"#000000\">
This is an example!<br>
Here's a variable: $aVariable<br>

</body>";

// Multi-line here-doc string
echo <<<END_OF_OUTPUT
<body bgcolor="#FFFFFF" text="#000000">
This is an example!<br>
Here's a variable: $aVariable<br>

</body>
END_OF_OUTPUT;

?>

These examples have the exact same output. However, you should notice how difficult it could be to read a multiline string when the double-quotes must be escaped. With too much escaping, your strings would, at times, become almost impossible to comprehend. Since here-doc doesn't require quotes to be escaped, it can make your code easier to read.

Using Short Tags

The other method of outputting large amounts of dynamic data is to use short tags. As discussed in Chapter 1, short tags are a shorthand way to make regular PHP tags shorter.

The following example uses the short tag that you've already seen:

<? echo "This echo statement is in short tags!"; ?>

NOTE

Recall from Chapter 1 that using short tags shortens the first tag because you remove the letters "php" from it; the closing tag remains the same. Also, the semicolon following the command shown here can be omitted because it is the only command within the PHP tags.

Using an echo statement for every dynamic element you wish to output works, but it's still a bit tedious to type "echo" every time. During the development of PHP, some PHP programmers were migrating to PHP from ASP (Microsoft's scripting environment known as Active Server Pages, which is somewhat similar to PHP). These programmers were used to ASP tags, which come in two varieties: the regular ASP tags, which, like PHP tags, separate ASP code from static output; and the ASP equals tag. The ASP equals tag added an equals sign to the opening ASP tag (hence the name "equals tag") and eliminated the need for an explicit command to print output.

PHP has a second short tag that was modeled after ASP's equals tag. Like ASP's equals tag, it shortens the amount of code it takes to output a value and eliminates the need for the echo statement by appending an equals sign to PHP's short tag.

NOTE

Remember that short tags must be enabled in PHP's configuration file for them to work. The short tag and the short equals tag are collectively classified as PHP's "short tags." If you experience problems or short tags don't work as expected, consult the configuration section of the PHP manual.

Take a look at the following excerpt, which puts PHP's short equals tag to use:

<?= "This is outputted automagically by the short equals tag!" ?>

Where the letters "php" would appear in a regular PHP tag, there is now an equals sign.

CAUTION

The equals sign must be directly attached to the tag—spaces separating the equals sign from the question mark are not allowed. Also, the short equals tag does not work with the regular PHP tag: Combining <?= with <?php to get <?php= will result in a generic parse error.

Now that you understand the basics of the short equals tag, let's take a look at its advantages. The short equals tag can significantly reduce the complexity of your code and increase its readability. Take a look at the following code segment, which doesn't use the short equals tag:

<?php
/* ch03ex06.php – demonstrates code using standard PHP tags with echo */

$title = "Example Title";
$text = "Here's some text!";

?>
<html>
<head><title><?php echo $title; ?></title></head>
<body><?php echo $text; ?></body>
</html>

Now compare it to the simpler version of the same code:

<?php
/* ch03ex07.php – demonstrates short equals tag */

$title = "Example Title";
$text = "Here's some text!";

?>
<html>
<head><title><?= $title ?></title></head>
<body><?= $text ?></body>
</html>

While both of these have the same output, the second one is quicker and easier to type. In fact, many developers prefer it to the tediousness of the first method.

CAUTION

Of these two methods, I will use the latter throughout this book to keep my code concise and as clear as possible. However, before adopting the short tags for use on any major project, you should ensure that your host will allow you to use short tags so you don't run into problems if your host has short tags disabled for some reason.

Here-doc Versus the Short Equals Tag

To summarize the differences between using here-doc or the short equals tag, here-doc can be handy in certain instances (like storing a long string to a variable), but it isn't usually a very good way to send output. For clarity, it's probably wiser to stick with the short equals tag or even regular PHP tags with an echo statement, if necessary. However, if you absolutely are stuck on using multiline strings to send output, here-doc is a better way to do it than double-quoted strings, stylistically.

So you can compare the two for yourself side-by-side, the following account information program has been provided using each method. The output is the same for both examples; a program like this would typically be used on an e-commerce or members-only site to tell the user important information about his account, such as his account number and the e-mail address he registered with.

Here's the here-doc version:

<?php
/* ch03ex08.php – displays account info using here-doc */

// Set up example account information
$user_name = "John Williams";
$user_email = "johnw@example.com";
$user_acctno = 1152;

// Display account info code
echo <<<END_HTML
<b>Name:</b> $user_name<br>
<b>E-Mail:</b> $user_email<br>
<b>Account Number:</b> $user_acctno<br>
END_HTML;

?>

And here's the short equals tag version of the same program:

<?php
/* ch03ex09.php – displays account info using equals tags */

// Set up example account information
$user_name = "John Williams";
$user_email = "johnw@example.com";
$user_acctno = 1152;

// Display account info code
?>
<b>Name:</b> <?= $user_name ?><br>
<b>E-Mail:</b> <?= $user_email ?><br>
<b>Account Number:</b> <?= $user_acctno ?><br>
<?php

// This space can be omitted, but is included to show that
// more code could be included here if desired.

?> 

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