
- •Initializing with Constructor Functions . . . . .
- •Into a Web page as a separate section. Although JavaScript code can
- •Is that standard php script delimiters are guaranteed to be available
- •In the block. Any text or lines between the opening /* characters and
- •2.7541 Are not integers; they are floating-point numbers. A floating-
- •Value 300
- •Is a value of 2.5, because 6 goes into 15 exactly 2.5 times. But if you
- •IsEven.Php.
- •Ing example,
- •Ing curly brace is on its own line following the function statements.
- •In php 3 and earlier, it was necessary to put a function definition
- •Is called an iteration. When the conditional expression evaluates
- •Including Files
- •13. Close your Web browser window.
- •Including Files
- •In php, you can also use two operators to combine strings. The first
- •Xhtml source code gen-
- •Input. Php provides several functions for manipulating the case of a
- •Is uppercase. If you need the reverse of ucfirst(), the lcfirst()
- •In some situations, you will need to find and extract characters and
- •Information Interchange, or ascii, which are numeric represen-
- •In comparison, the following preg_match() function returns a value
- •In the pattern is optional. The following code demonstrates how to
- •Values; any strings you validate against a regular expression must
- •Value of 1 because the top-level domain contains a valid value of .Com.
- •Is submitted using the “post” method, the form data is embedded in
- •Validating String Data
- •Xhtml tags or character entities. The message field is a text string
- •Value of the header element. For example:
- •Xhtml code within a php script section.
- •Is typically the person who created the resource. Otherwise, the net-
- •If even a single character of the Web page is sent prior to sending
- •Variables to the file_put_contents() function.
- •Xhtml hyperlink. To download a file from outside the xhtml
- •If...Else statement to display the appropriate version of the mes-
- •Iterating Through an Array
- •Iterating Through an Array
- •In Chapter 2, you learned how to use a foreach statement to iterate
- •Iterating Through an Array
- •Iterating Through an Array
- •In comparison, the following code declares and initializes
- •If ((!file_exists("MessageBoard/messages.Txt"))
- •Values from the array to create a thumbnail gallery of images in which
- •Introduction to Databases
- •Including php, allow you to create Web pages that can read and write
- •Introduction to Databases
- •Information that can be organized into ordered sets of data, and
- •Information. Each recipe in a recipe database, for instance, is a single
- •Introduction to Databases
- •Index, which identifies records in a database to make retrievals and
- •In a single table. However, you might want to break the information
- •Into multiple tables to better organize it into logical sets. Another
- •Information in one of the tables confidential and accessible only by
- •Is the employee information table from Figure 7-1. The related table
- •Is a payroll table that contains confidential salary and compensation
- •Information. Notice that each table contains an identical number of
- •Introduction to Databases
- •Introduction to Databases
- •In a junction
- •Introduction to Databases
- •In a relational format is called a relational database management
- •Is a standard data manipulation language among many dbmSs.
- •Into the query area at the top of the screen or by dragging tables and
- •It is important to understand that even though many dbmSs sup-
- •Introduction to Databases
- •If you ever
- •Is. In comparison, the bigint data type stores integer values between
- •5 Rows in set (0.00 sec)
- •Int);[enter ]
- •Important, these two tabs can cause you to lose all of the data in the
- •Internet Explorer to export the table, click the Save button in the File
- •Ifies the table being changed and the change to make.
- •It easier for you to write php code that can be used with a variety of
- •Information about queries that match one of the following formats:
- •Various types of actions, depending on the type of query.
- •Include fields for the date and time of the flight, flight number, and
- •In the ChineseZodiac folder and upload the file to the server. Open
- •Including white space,
- •Information on a Web server. When you start a new session, the
- •Introduction to Object-Oriented Programming
- •Introduction to Object-Oriented
- •Variables associated with an object are called properties or attributes.
- •In the Loan object example, a function that calculates the number of
- •Introduction to Object-Oriented Programming
- •Introduction to Object-Oriented Programming
- •Include instances of objects inherit the object’s functionality.
- •In this chapter, you will create the Web site for an online order form
- •In an online store application. The application includes information
- •Ity of building a working online store. Online store classes are very
- •Information and products. The OnlineStore class requires that store
- •Information is stored in a table containing six fields: storeId, name,
- •Information. Instead, the class simply uses session iDs to keep track
- •Variable and function as necessary, without bothering with all this
- •In a class
- •Is developed. Imagine what would happen if Microsoft distributed
- •Ing class is invalid because it does not include an access specifier:
- •If they will not be supported by future xhtml versions or are not
- •Xhtml standards. To review the guide of current w3c css specifi-
- •Information to remind yourself or others of what the code is doing. A
- •Xhtml document to the external style sheet. This link informa-
- •If you select Apache from the WampServer menu and select Service
- •Ing code uses the number_format() function to add comma separa-
- •In data that a user submits to a php script.
- •Value of “On” and the display_startup_errors directive is assigned
- •Instead. By looking at the source code, you could see that the value of
- •Ing engine can even help locate logic errors.
- •In Chapter 8, along with the equivalent mssql_* functions, where
- •Inline styles, 632
- •Xhtml, 620–635 (continued)
Xhtml code within a php script section.
Comprehension
Check
•
The
to send form data via e-mail when the form has been successfully
completed and validated.
• All-in-One Web forms combine the data entry form page and the
data processing script into a single script.
• The
isset() function determines if the entered value has been ini-tialized (or set).
• URL tokens use the get method and additional data appended to
the URL to submit information to a PHP script.
• Web page templates combine static elements and a dynamic
content section within a Web page.
• Web page templates can use the
include() function within aconditional or switch statement to display dynamic content from
different include files within the same section of the template.
219
Comprehension Check
1.
Which of the following autoglobals can you use to access
submitted form values? (Choose all that apply.)
a. $_GET
b. $_POST
c. $_SERVER
d. $_REQUEST
2.
Which of the following separates the URL from the form data
in a get request?
a. ?
b. &
c. =
d. +
3.
Which of the following separates multiple name/value pairs
from each other in a get request?
a. ?
b. &
c. =
d. +

CHAPTER
4
Handling
User Input
4.
5.
What
is the maximum length of a value in a get request?
Describe
the difference in how data is sent to the Web server
for
the get and post methods.
Contrast
the two-part Web form with the All-in-One Web
form.
What
are magic quotes and why are they used?
Which
function removes the slashes that are added by magic
quotes?
The
empty()
function
is used to do which of the following?
(Select
all that apply.)
a.
Clear the value of a variable.
b.
Check if the length of a string variable is 0.
c.
Check to see if the value of a variable is NULL.
d.
Check to see if the value of a numeric variable is 0.
220
6.
7.
8.
9.
10.
The is_*()
family
of functions can be used to verify that the
user
entered the correct data type in a form field. True or
False?
11. A user should fix each data entry error before being notified
of the next one. True or False?
12. A(n)form redisplays a form with the previ-
ously entered values already filled in.
a. error
b. sticky
c. prefilled
d. Web
13. Explain the purpose of advanced escaping from XHTML.
14. Explain why the isset() function is not an inverse of the
empty() function.

Reinforcement
Exercises
15.
Thefunction can be used to determine if
data
has been submitted to an All-in-One form.
a. is_posted()
b. submitted()
c. isset()
d. data_found()
16. URL tokens use the post method. True or False?
17. Web page templates are made of
sections.
a. form, script
b. image, text
c. static, dynamic
d. content, template
18. With Web page templates, every page needs to be modified to
change an image in the header section. True or False?
19. Describe two methods used to navigate within a Web page
template.
20. Theautoglobal contains all of the elements
of both the
$_GET and $_POST autoglobals.a. $_REQUEST
b. $_RESPONSE
c. $_FORM
d. $_SESSION
and
221
Reinforcement Exercises
Exercise 4-1
Create a Web form to help in creating “Jumble” puzzles. Create a
form that has four input fields named Word1, Word2, Word3, and
Word4, as well as “Reset” and “Submit” buttons. Create a form pro-
cessing script that verifies that all four words are entered, that all
of them contain only letters, and that all four are between 4 and 7
CHAPTER
4
Handling
User Input
characters
long. Once all of the words have been verified as correct,
use
the strtoupper()
and
str_shuffle()
functions
to produce four
jumbled
sets of letters.
To
create the Jumble Maker form:
222
1.
Create
a new document in your text editor. Type the
!DOCTYPE
declaration,
<html>
element,
header information,
and
<body>
element.
Use the strict DTD and “Jumble Maker”
as
the content of the <title>
element.
Add
the following XHTML form tags in the body of the
document:
<form
action=
"process_JumbleMaker.php"
method="post">
Word 1: <input type="text" name="Word1" /><br />
Word 2: <input type="text" name="Word2" /><br />
Word 3: <input type="text" name="Word3" /><br />
Word 4: <input type="text" name="Word4" /><br />
<input type="reset" value="Clear Form" />
<input type="submit" name="Submit" value="Send
Form" />
</form>
2.
3.
Save the document as JumbleMaker.html in the Projects
directory for Chapter 4.
Create a new document in your text editor. Type the
!DOCTYPE declaration, <html> element, header information,
and <body> element. Use the strict DTD and “Jumble Maker”
as the content of the <title> element.
Add the opening and closing tags for the PHP script section
in the body of the document:
<?php
?>
4.
5.
6.
Add the displayError() function to the script section. This
function displays the error message, and takes two param-
eters: $fieldName, which is the name of the field as it appears
on the Web form; and $errorMsg, which describes the error
for the user. There is no return value for this function.
function displayError($fieldName, $errorMsg) {
global $errorCount;
echo "Error for \"$fieldName\": $errorMsg<br />\n";
++$errorCount;
}
Reinforcement
Exercises
7.
Create
a second function called validateWord()
below
the
displayError()
function.
This function takes two parame-
ters.
The first parameter, $data,
is a string to be validated. The
second
parameter, $fieldName,
is the name of the form field.
The
function returns the $data
parameter
after it has been
cleaned
up. Notice that the function uses the global variable
$errorCount.
function
validateWord($data, $fieldName) {
global
$errorCount;
if (empty($data)) {
displayError($fieldName,"This field is
required");
$retval = "";
} else { // Only clean up the input if it isn't
// empty
$retval = trim($data);
$retval = stripslashes($retval);
if ((strlen($retval)<4) ||
(strlen($retval)>7)) {
displayError($fieldName,"Words must be
at least four and at most
seven letters long");
}
if (preg_match("/^[a-z]+$/i",$retval)==0) {
displayError($fieldName,"Words must be
only letters");
}
}
$retval = strtoupper($retval);
$retval = str_shuffle($retval);
return($retval);
}
223
8.
Immediately after the validateWord() function, declare and
initialize a new variable called $errorCount and a new array
called $words[] as follows:
$errorCount = 0;
$words = array();
9.
Add assignment statements for the $words array variable to
receive the output of the validateWord() function for each
form field:
$words[]
$words[]
$words[]
$words[]
=
=
=
=
validateWord($_POST['Word1'],
validateWord($_POST['Word2'],
validateWord($_POST['Word3'],
validateWord($_POST['Word4'],
"Word
"Word
"Word
"Word
1");
2");
3");
4");

CHAPTER
4
Handling
User Input
10.
Add a conditional statement immediately after the values of
$words
have
been assigned. This statement will display the
total
number of errors found or the shuffled words if there
were no errors.
224
if ($errorCount>0)
echo "Please use the \"Back\" button to
re-enter the data.<br />\n";
else {
$wordnum = 0;
foreach ($words as $word)
echo "Word ".++$wordnum.": $word<br />\n";
}
11. Save the document as process_JumbleMaker.php in the
Projects directory for Chapter 4.
12. Upload JumbleMaker.html and process_JumbleMaker.php to
the Web server.
13. Open the JumbleMaker.html page in the Web browser
by entering the following URL: http://<yourserver>/
PHP_Projects/Chapter.04/Projects/JumbleMaker.html.
14. Test the form. It should only show the jumbled results if all
four words were entered correctly.
15. Close your Web browser window.
Exercise 4-2
In this exercise, you will create an All-in-One form that is a work-
ing “Contact Me” page. This page will have inputs for the subject,
the sender’s name, the sender’s e-mail address, and the message. The
form will also send a copy of the message to the sender.
1.
Create a new document in your text editor. Type the
!DOCTYPE declaration, <html> element, header information,
and <body> element. Use the strict DTD and “Contact Me” as
the content of the <title> element.
Add the opening and closing tags for the PHP script section
in the body of the document:
<?php
?>
2.
Reinforcement
Exercises
3.
Add
a function called validateInput().
This function takes
two
parameters. The first parameter, $data,
is a string to be
validated.
The second parameter, $fieldName,
is the name
of
the form field. The function returns the $data
parameter
after
it has been cleaned up. Notice that the function uses the
global
variable $errorCount.
function
validateInput($data, $fieldName) {
global
$errorCount;
if (empty($data)) {
echo "\"$fieldName\" is a required field.<br
/>\n";
++$errorCount;
$retval = "";
} else { // Only clean up the input if it isn't
// empty
$retval = trim($data);
$retval = stripslashes($retval);
}
return($retval);
}
225
4.
Add a function called validateEmail() immediately after the
validateInput() function. This function is almost exactly
like the validateInput() function, but it adds a regular
expression test to validate that the entered e-mail address is
in the correct format. Note that the regular expression used is
the same one introduced in Chapter 3.
function validateEmail($data, $fieldName) {
global $errorCount;
if (empty($data)) {
echo "\"$fieldName\" is a required
field.<br />\n";
++$errorCount;
$retval = "";
} else { // Only clean up the input if it isn't
// empty
$retval = trim($data);
$retval = stripslashes($retval);
$pattern = "/^[\w-]+(\.[\w-]+)*@" .
"[\w-]+(\.[\w-]+)*" .
"(\.[[a-z]]{2,})$/i";
if (preg_match($pattern, $retval)==0) {
echo "\"$fieldName\" is not a valid e-mail
address.<br />\n";
++$errorCount;
}
}
return($retval);
}
CHAPTER
4
Handling
User Input
5.
Add
a function called displayForm()
immediately
after the
validateEmail()
function.
This function takes one param-
eter
for each form field, and displays the form. It uses the
parameters
for sticky form functionality.
function
displayForm($Sender, $Email, $Subject,
$Message)
{
?>
<h2
style = "text-align:center">Contact Me</h2>
<form
name="contact" action="ContactForm.php"
method="post">
<p>Your Name: <input type="text" name="Sender"
value="<?php
echo $Sender; ?>" /></p>
<p>Your E-mail: <input type="text" name="Email"
value="<?php echo $Email; ?>" /></p>
<p>Subject: <input type="text" name="Subject"
value="<?php
echo $Subject; ?>" /></p>
<p>Message:<br />
<textarea name="Message"><?php echo $Message;
?></textarea></p>
<p><input type="reset" value="Clear Form" />
<input type="submit" name="Submit"
value="Send Form" /></p>
</form>
<?php
}
226
6.
Immediately after the displayForm() function, declare and
initialize a set of variables as follows:
$ShowForm = TRUE;
$errorCount = 0;
$Sender = "";
$Email = "";
$Subject = "";
$Message = "";
7.
Next, add the following code to check for and validate the
input. Note that $_POST['Email'] is checked with the
validateEmail() function instead of the validateInput()
function.
if (isset($_POST['Submit'])) {
$Sender =
validateInput($_POST['Sender'],"Your Name");
$Email =
validateEmail($_POST['Email'],"Your E-mail");
$Subject =
validateInput($_POST['Subject'],"Subject");
$Message =
validateInput($_POST['Message'],"Message");
Reinforcement
Exercises
if
($errorCount==0)
$ShowForm
= FALSE;
else
$ShowForm = TRUE;
}
8.
Next, add a conditional statement that checks the value
of $ShowForm. If $ShowForm is TRUE, the form is displayed.
Otherwise, an e-mail message is sent and a status message is
displayed. Note that a copy is sent to the sender.
if ($ShowForm == TRUE) {
if ($errorCount>0) // if there were errors
echo "<p>Please re-enter the form
information below.</p>\n";
displayForm($Sender, $Email, $Subject,
$Message);
}
else {
$SenderAddress = "$Sender <$Email>";
$Headers = "From: $SenderAddress\nCC:
$SenderAddress\n";
// Substitute your own email address for
// recipient@example.com
$result = mail("recipient@example.com",
$Subject, $Message, $Headers);
if ($result)
echo "<p>Your message has been sent. Thank you, "
. $Sender . ".</p>\n";
else
echo "<p>There was an error sending your
message, " .
$Sender . ".</p>\n";
}
227
9.
Save the document as ContactForm.php in the Projects
directory for Chapter 4 and upload the document to the Web
server.
10. Open ContactForm.php by entering the following URL:
http://<yourserver>/PHP_Projects/Chapter.04/Projects/
ContactForm.php. Verify that the form validates the input
fields correctly, redisplays the sticky form when there are
errors, and sends the e-mail message when there are no
errors.
11. Close your Web browser window.

CHAPTER
4
Handling
User Input
Exercise
4-3
The
strip-
slashes()
function was
introduced
earlier in this chapter. The
htmlentities() func-
tion was discussed in
Chapter 3.
228
Create an include file to assist with debugging Web forms. The
include file should create a table to display the contents of the
$_REQUEST autoglobal. The table will have two columns showing
each name/value pair. Use the advanced foreach statement syntax to
retrieve the index and value of each element of the $_REQUEST array.
Be sure to use the stripslashes() and htmlentities() functions
before displaying the text in the Web page. Save the document as inc_
requestDump.php. Create a second document to test the include
file. Save the second document as RequestDump.php.
Exercise 4-4
Create a two-part form that calculates an employee’s weekly gross
salary, based on the number of hours worked and an hourly wage
that you choose. Use an HTML document named Paycheck.html
as a Web form with two text boxes—one for the number of hours
worked and one for the hourly wage. Use a PHP document named
Paycheck.php as the form handler. Compute any hours over 40 as
time-and-a-half. Be sure to verify and validate the submitted form
data and provide appropriate error messages for invalid values.
Exercise 4-5
Create an All-in-One sticky form to solve the common “two trains
are moving toward each other” word problem. The form should
have three inputs, all numbers greater than 0: the speed of Train A
($SpeedA), the speed of Train B ($SpeedB), and the distance between
the two trains ($Distance). For this problem, you will need the fol-
lowing equations:
$DistanceA = (($SpeedA / $SpeedB) * $Distance) /
(1 + ($SpeedA / $SpeedB));
$DistanceB = $Distance - $DistanceA;
$TimeA = $DistanceA / $SpeedA;
$TimeB = $DistanceB / $SpeedB;
In the preceding equations, $DistanceA and $DistanceB are the dis-
tances traveled by Trains A and B, respectively; $TimeA and $TimeB
are how long Trains A and B traveled, respectively ($TimeA should
equal $TimeB). If $SpeedA or $SpeedB is allowed to be 0, PHP will
display a “division by zero not allowed” error. Save the document as
TwoTrains.php in the Projects directory for Chapter 4.

Discovery
Projects
Discovery
Projects
In
the following projects, you will continue to design and develop
the
Chinese Zodiac site that you began in Chapter 1. All files
for
the Chinese Zodiac site will be saved in a directory named
ChineseZodiac
in the base Web folder on the server.
229
The
following projects will add interactivity to the Chinese Zodiac
Web
page template by displaying alternative content in the dynamic
content
section of the index.php file when the user clicks a button or
activates
a hyperlink.
Discovery
Project 4-1
In
your text editor, create new include files with a placeholder for
page
content for each of the pages identified by the buttons and text
links.
(The inc_home_page.php file has already been created.) The
contents
of the pages will be populated in later projects.
Target
Page
site_layout
control_
structures
string_functions
web_forms
midterm_
assessment
state_information
user_templates
final_project
Table
4-3
Include
Filenames
inc_site_layout.php
inc_control_structures.php
inc_string_functions.php
inc_web_forms.php
inc_midterm_assessment.php
inc_state_information.php
inc_user_templates.php
inc_final_project.php
Pages
for Discovery Project 4-1
Page
Content
[Insert
site layout content here]
[Insert
control structure content here]
[Insert
string function content here]
[Insert
Web forms content here]
[Insert
midterm assessment content
here]
[Insert
state information content here]
[Insert
user template content here]
[Insert
final project content here]
Save
the files and upload them to the Includes folder in the
ChineseZodiac
folder on the server.
Discovery
Project 4-2
1.
Reopen
the inc_button_nav.php file created in Discovery
Project
2-2. The file is in the Includes folder in the
ChineseZodiac
folder. Insert the code to convert the first of
eight
button images to hyperlinks that display the destination
CHAPTER
4
Handling
User Input
file
in the dynamic data section of the Chinese Zodiac Web
page
template (index.php).
<a
href = "index.php?page=home_page">
<img
class="btn" src="Images/ButtonHomePage.gif"
alt="[Home
Page]" title="Home Page"style =
"border:0"
/></a><br />
230
2.
Continue to add code for the other seven button images
targeting the content to the dynamic data section. Use the
appropriate “Target Page” value from Table 4-3 as the value of
each page parameter.
Save the file and upload it to the Web server.
3.
Discovery Project 4-3
1.
Reopen the inc_text_links.php file created in Discovery
Project 2-2 in your text editor. The file is stored in the
Includes folder in the ChineseZodiac folder. Modify the first
text hyperlink to display the destination file in the dynamic
data section of the Chinese Zodiac Web page template
(index.php), as shown in the following code:
<a href = "index.php?page=home_page">Home Page</a>
2.
Continue including additional code for the other seven hyper-
links in the text links bar, targeting the content to the dynamic
data section. Use the appropriate “Target Page” value from
Table 4-3 as the value of each page parameter.
Save the file and upload it to the Web server.
3.
Discovery Project 4-4
1.
Reopen the index.php file created in Discovery Project 2-2
in your text editor. The file is in the ChineseZodiac folder.
Replace the script section for the dynamic content section of
the Web page template.
if (isset($_GET['page'])) {
switch ($_GET['page']) {
case 'site_layout':
include('Includes/inc_site_layout.php');
break;
case 'control_structures':
include('Includes/' .
'inc_control_structures.php');
break;
Discovery
Projects
case
'string_functions':
include('Includes/'
.
'inc_string_functions.php');
break;
case 'web_forms':
include('Includes/inc_web_forms.php');
break;
case 'midterm_assessment':
include('Includes/' .
'inc_midterm_assessment.php');
break;
case 'state_information':
include('Includes/' .
'inc_state_information.php');
break;
case 'user_templates':
include('Includes/' .
'inc_user_templates.php');
break;
case 'final_project':
include('Includes/' .
'inc_final_project.php');
break;
case 'home_page': // A value of
// 'home_page' means
// to display the
// default page
default:
include('Includes/inc_home.php');
break;
}
}
else // If no button has been selected, then display
// the default page
include('Includes/inc_home.php');
231
2.
Save the file and upload it to the ChineseZodiac folder on the
Web server.
Open the index.php page in the Web browser by entering the
following URL: http://<yourserver>/ChineseZodiac/index.php.
Verify that the content of the dynamic content section
changes each time you click a button or activate a text
hyperlink.
Close your Web browser window.
3.
4.
5.

CHAPTER
4
Handling
User Input
Discovery
Project 4-5
Reopen
inc_home_links_bar.php (created in Discovery Project 3-3)
in
your text editor and enclose the two labels in <a>
tags.
The
value
for the href
attribute
of both <a>
tags
will be index.php,
but
each page will have different URL tokens to specify the infor-
mation
that should be displayed. You will continue to use the
page
URL
token to specify the home page by using the value
home_page.
Additionally, you will use the section
URL
token
with
different values to determine which of the two versions of
the
home page to display: either the one with the PHP informa-
tion
(section=php)
or the one with the Chinese zodiac informa-
tion
(section=zodiac).
For the PHP text link, the href
value
of
the
<a>
tag
should be index.php?page=home_page§ion=php.
For
the Chinese zodiac text link, the href value of the <a>
tag
should
be index.php?page=home_page§ion=zodiac.
Save
inc_home_links_bar.php
and upload the file to the Includes folder in
the
ChineseZodiac folder on the server.
In
your text editor, reopen the inc_home.php document that you
created
in Discovery Project 2-2. Replace the placeholder [Insert
home
page content here] with a PHP code section that includes
inc_home_links_bar.php
at the top of the file.
At
the end of the PHP code section, add the following code:
if
(isset($_GET['section'])) {
switch
($_GET['section']) {
case 'zodiac':
include('Includes/inc_chinese_zodiac.php');
break;
case 'php': // A value of 'php' means
// to display the default page
default:
include('Includes/inc_php_info.php');
break;
}
}
else // If no section has been selected, then display the
// default page
include('Includes/inc_php_info.php');
232
Save the file as inc_home.php and upload it to the Includes folder in
the ChineseZodiac folder on the server.
Open http://<yourserver>/ChineseZodiac/index.php in the browser
and test each button and text hyperlink to verify that the content of
the dynamic data section changes when a button or text link is clicked.

CHAPTER
Working
with Files
and
Directories
In
this chapter, you will:
Understand
file types and permissions
Work
with directories
Upload
and download files
Write
data to files
Read
data from files
Open
and close a file stream
Manage
files and directories
5
CHAPTER
5
Working
with Files and Directories
234
Many
programming tasks for a Web site require some form of data
storage.
User files need to be uploaded and downloaded. Form data
needs
to be saved and retrieved. Online calendars and blogs need to
be
updated. One method of performing all of these tasks is through
files
stored on the Web server. In this chapter, you will study how to
read,
write, and manipulate files.
Understanding
File Types
and
Permissions
You
need to understand two important file concepts before you can
work
with files in PHP. The first concept is file types, which affect
how
information is stored in files and retrieved from them. The
second
concept is file permissions, which determine the actions
that
a specific user can and cannot perform on a file.
Understanding
File Types
In
PHP, you can specify a file as one of two types: binary or text. A
binary
file is
a series of characters or bytes for which PHP attaches no
special
meaning. Any structure to the data is determined by the appli-
cation
that reads from or writes to the file. A text
file,
in contrast, is
assumed
to have only printable characters and a small set of control
or
formatting characters. The formatting characters are the binary
equivalents
of the escape sequences you learned in Chapter 3, and are
listed
in Table 5-1.
Escape
Sequence
\t
\r
\v
\f
\n
Meaning
Horizontal
tab
Line
feed
Vertical
tab
Form
feed
Carriage
return
Decimal
9
10
11
12
13
Byte
Value
OctalHexadecimal
011
012
013
014
015
09
0A
0B
0C
0D
Table 5-1
Control characters in a text file
Different operating systems use different escape sequences to identify
the end of a line. UNIX/Linux platforms use the \n carriage return
escape sequence, Macintosh applications usually use the \r line feed
escape sequence, and Windows operating systems use the \n carriage
return escape sequence followed by the \r line feed escape sequence.
The following code shows examples from all three operating systems:

Understanding
File Types and Permissions
This
is how you end a line on UNIX/Linux platforms.\n
This
is how you end a line on Windows operating systems.\n\r
This
is how you end a line on Macintosh operating
systems.\r
Prior to OS X,
all Macintosh
applications
and the
Macintosh
operating system used
the \r line feed escape
sequence to identify the
end of a line. Starting
with OS X, the Macintosh
operating system is built
on a Linux core. So,
although most Macintosh
applications still use the
\r escape sequence as
the end-of-line marker,
most command-line and
operating system pro-
grams use the UNIX/
Linux \n carriage return
escape sequence.
If you do not use the correct end-of-line escape sequence, you may
have problems when working with text files on different platforms.
For example, each name in the following list ends with the \n carriage
return escape sequence, as required for UNIX/Linux operating
systems:
Blair, Dennis\n
Hernandez, Louis\n
Miller, Erica\n
Morinaga, Scott\n
Picard, Raymond\n
235
If you open a text file that contains the preceding lines in the Notepad
text editor on a Windows operating system, the \n characters are not
recognized as end-of-line markers. Instead, all of the separate strings
are displayed as one continuous string, and the font’s “nondisplayable
character” symbol (in this case, a rectangle) is displayed in place of
the \n characters, as shown in Figure 5-1.
Figure 5-1
Displaying a UNIX/Linux text file using Notepad in Windows
For the lines to display correctly in Windows, they must end with the
\n\r escape sequence pair, as follows:
Blair, Dennis\n\r
Hernandez, Louis\n\r
Miller, Erica\n\r
Morinaga, Scott\n\r
Picard, Raymond\n\r
The PHP file functions that you study in this chapter can usually
accommodate any of these escape sequences and end lines in a text
file appropriately, regardless of the operating system. Although the
examples in this book use the \n carriage return escape sequence
that is supported by UNIX/Linux operating systems, the PHP scripts
you write will function correctly on any platform. However, keep in
mind that if you attempt to open a text file that does not contain the
required characters for the current operating system, the line breaks

CHAPTER
5
Working
with Files and Directories
may
not appear correctly in your text editor. As a general rule, you
should
choose the appropriate end-of-line escape sequence for your
Web
server.
Working
with File Permissions
236
See
your
operating
system’s
documenta-
tion for
information on how to
manually set permissions
for resources such as
files and directories.
PHP
modeled the
chmod()
function
after the
UNIX chmod utility, so
values for the mode
parameter of the
chmod() function match
those in the chmod utility.
For other operating
systems, the chmod()
function converts the
mode flags into the
equivalent permissions
for the underlying
operating system.