
- •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)
CHAPTER
4
Handling
User Input
controls
(text input boxes, radio buttons, check boxes, selection
lists,
text area boxes), and a submit button to send the form values
to
the server for processing. A reset button to clear the form data
is
optional.
192
Adding
an action Attribute
The
<form>
opening
tag requires an action
attribute.
The value of the
action
attribute
identifies the program on the Web server that will
process
the form data when the form is submitted. A PHP script is
often
used to process form data.
<form
action="http://www.example.com/HandleFormInput.php">
Adding
a method Attribute
The
opening <form>
tag
must also contain a method
attribute,
which
defines
how the form data is submitted to the server. The value of
the
method
attribute
will be either “post” or “get.” When form data
the
request message. When form data is submitted using the “get”
method,
the form data is appended to the URL specified in the form’s
action
attribute.
Earlier
in this chapter, you were introduced to two autoglobals,
$_POST
and
$_GET,
which allow you to access the values that are sub-
mitted
to a PHP script from a Web form. When a Web form is sub-
mitted,
PHP automatically creates and populates two global arrays:
the
$_POST
array,
which contains values of forms that are submitted
using
the post method, and the $_GET
array,
which contains values
from
forms that are submitted using the get method.
When
you click a form’s Submit button, each field on the form is sent
to
the Web server as a name/value pair. When the post method is
used,
the name portion of the name/value pair becomes the key, or
index,
of an element in the $_POST
autoglobal
array and the value por-
tion
is assigned as the value of the array element. The get method is
used
in the same way, except that the name portion of the name/value
pair
becomes the key of an element in the $_GET
autoglobal
array.
When
you use the get method to submit form data to the processing
script,
the form data is appended to the URL specified by the action
attribute.
Name/value pairs appended to the end of a URL are called
URL
tokens.
The form data is separated from the URL by a question
mark
(?),
the individual elements are separated by an ampersand (&),
and
the element name is separated from the value by an equal sign
(=).
Spaces in the name and value fields are encoded as plus signs (+),Is submitted using the “post” method, the form data is embedded in
Building
XHTML Web Forms
and
all other characters except letters, numbers, hyphens (-),
under-
scores
(_),
and periods (.)
are encoded using a percent sign (%)
fol-
lowed
by the two-digit hexadecimal representation of the character’s
ASCII
value. For example:
http://www.example.net/process_Scholarship.php?fName=
John&lName=Smith&Submit=Send+Form
The
get
method
restricts the
number of
characters
that can be appended to
a single variable to 100.
An HTTP
request with
URL tokens
is not
secure. It is
stored in plain text in log
files on any machine
between the client and
server computers, as well
as on the client and
server computers them-
selves. Because the get
method encodes the data
in the URL, it would not
be practical to use the
get method to submit
sensitive information,
such as Social Security
numbers or passwords.
193
In the preceding example, three form elements were submitted to the
process_Scholarship.php script as URL tokens: fName, which is set to
“John”;
lName, which is set to “Smith”; and “Submit” (the name of thesubmit button), which is set to “Send Form”, the value assigned to the
submit button.
The get method is useful as a debugging technique because it allows
you to see the names and values that are being sent to the Web server.
The get method is also useful for creating static links to a dynamic
server process, as you will learn later in this chapter.
Because many forms request confidential information, such as Social
Security numbers and passwords, or may contain a field that requires
the user to enter more than 100 characters, examples will use the post
method to submit form data for the remainder of this book.
To create an XHTML form that contains two text input boxes for
users to enter their first and last names and two buttons to clear or
submit the form data:
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 “Scholarship
Form” as the content of the <title> element.
Add the following XHTML content to the document body:
<h2 style="text-align:center">Scholarship Form</h2>
<form name="scholarship" action=
"process_Scholarship.php"
method="post">
<p>First Name: <input type="text" name="fName" /></p>
<p>Last Name: <input type="text" name="lName" /></p>
<p><input type="reset" value="Clear Form" />
<input type="submit" name="Submit" value=
"Send Form" />
</form>
2.
3.
Save the document as Scholarship.html in the Chapter direc-
tory for Chapter 4. Because Scholarship.html contains only
XHTML markup, you can view this document in the browser
locally. You should see the Web page shown in Figure 4-2.

CHAPTER
4
Handling
User Input
194
Figure
4-2
4.
The
scholarship form
Close
your Web browser window.
Short
Quiz
1.
Explain
the function of the action
and
method
attributes
in
the
opening <form>
tag.
Explain
the difference(s) in how form data is submitted using
the
post and get methods.
Describe
the limitations of using the get method to submit
form
data.
2.
3.
Processing
Form Data
The
second half of the procedure for using Web forms is processing
the
form data once it is submitted. This is done in a form
handler—a
program
or script that processes the information submitted from a
Web
form. A form handler includes code for verifying that the user
entered
the minimum amount of data needed to process the form,
validating
entered data to ensure that it is appropriate for the field,
performing
any tasks needed for the data submitted, and returning
appropriate
output as a Web page.
Retrieving
Submitted Data
After
the user fills out the fields in the Scholarship.html Web form
and
clicks the submit button using the post method, the names
(fName,
lName,
and Submit)
that were assigned to the controls in the
Scholarship
form automatically become keys in the $_POST
autoglobal
Processing
Form Data
array.
Also, the values the user enters in the First Name and Last
Name
input boxes (“John” and “Smith” in the following example)
and
the
value assigned to the submit button (“Send Form”) become the
values
in the $_POST
array
that can be accessed by the processing
script.
To
create a form handler for the Scholarship.html form:
1.
195
Create
a new document in your text editor. Type the
!DOCTYPE
declaration,
<html>
element,
header information,
and
<body>
element.
Use the strict DTD and “Scholarship
Form”
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.
3.
Add
the following code to retrieve and display the data
entered
on the form:
$firstName
= $_POST['fName'];
$lastName
= $_POST['lName'];
echo
"Thank you for filling out the scholarship form,
".$firstName."
".$lastName . ".";
4.
Save the document as process_Scholarship.php in the
Chapter directory for Chapter 4.
Upload both Scholarship.html and process_Scholarship.php
to the server and then open Scholarship.html in the Web
browser by entering the following URL: http://<yourserver>/
PHP_Projects/Chapter.04/Chapter/Scholarship.html.
Enter a first name and last name in the appropriate fields and
submit the form to the process_Scholarship.php form handler.
Figure 4-3 shows sample output in a Web browser window.
5.
6.
Figure 4-3
7.
Output of the scholarship form handler
Close your Web browser window.

CHAPTER
4
Handling
User Input
Handling
Special Characters
The
previous example displays correctly unless the user enters an
apostrophe
in the First Name or Last Name text box on the Web
form.
Recall from Chapter 3 that you should use escape sequences for
special
characters in text strings, especially single or double quotes,
because
they may cause problems when the PHP scripting engine
attempts
to identify the end of a string. Because the data a user sub-
mits
to a PHP script may contain single or double quotes, you should
use
escape sequences for any user data your script receives, especially
before
you write it to a data source, such as a text file or database.
Older
versions of PHP include a feature called magic
quotes,
which
automatically
adds a backslash (\)
to any single quote ('),
double
quote
("),
or NULL character contained in form data that a user
submits
to a PHP script. For example, if you enter a last name with
an
apostrophe (such as “O’Hara”) in the Last Name text box in the
scholarship
form and then submit the form to a PHP script, magic
quotes
automatically escape the single quote, and the output appears
as
shown in Figure 4-4.
196
Figure
4-4
The
entered string from the Web form with magic quotes
Remember
that you can
check
whether any
of the magic
quote directives are
enabled by running the
phpinfo() function
that you used in Chapter
1. When you revisit the
PHPTest.php script you
created in Chapter 1, you
will see the
magic_quotes_gpc,
magic_quotes_
runtime, and magic_
quotes_sybase direc-
tives listed under the PHP
Core section.
Magic quotes are enabled within your php.ini configuration file with
the directives listed in Table 4-2.
Directive
magic_quotes_gpc
magic_quotes_runtime
magic_quotes_sybase
Description
Applies magic quotes to any user-submitted
data
Applies magic quotes to runtime-generated
data, such as data received from a database
Applies Sybase-style magic quotes, which
escape special characters with a single quote
(') instead of a backslash (\)
Table 4-2
Magic quote directives
By default, magic_quotes_gpc is the only magic quote directive
enabled in the php.ini configuration file.

Processing
Form Data
Magic
quotes are unpopular with programmers because it’s easy to
forget
whether they are enabled or disabled in PHP on a particular
server.
Many PHP programmers have spent hours trying to deter-
mine
why backslashes were being added to data their scripts received,
only
to discover that the culprit was a magic quote directive in the
php.ini
configuration file. You should ask your ISP to disable magic
quotes
in the php.ini configuration file.
Fortunately,
PHP provides an alternate method to escape strings,
even
if magic quotes are disabled. The addslashes()
function
accepts
a
single argument representing the text string you want to escape
and
returns a string containing the escaped string. For example,
assume
that a visitor to the scholarship form page enters the last
name
“O’Hara”. If magic quotes are enabled, the $_POST['lName']
autoglobal
element contains the value “O\’Hara”. The following code
escapes
the single quote in the last name O’Hara in the same manner;
the
output will be the same as shown in Figure 4-4:
$firstName
= addslashes($_POST['fName']);
$lastName
= addslashes($_POST['lName']);
echo
"Thank you for filling out the scholarship form, " .
$firstName
. " " . $lastName . ".";
See Appendix
D for an expla-
nation of secu-
rity issues
associated
with magic quotes.
197
The existence of the addslashes() function is actually another reason
why magic quotes are unpopular. If you execute the addslashes()
function on user-submitted data when magic quotes are turned on,
you will get unexpected results. First, magic quotes will add a slash
before the apostrophe (O\'Hara). Then the addslashes() function
will add a slash before both the slash and the apostrophe (O\\\'Hara).
The result is that three slashes are added when you only want one. For
example, if you execute the preceding code when magic quotes are
enabled, the text string appears as shown in Figure 4-5.
Because of
the problems
they can
cause, you
should ask
your ISP to turn off magic
quotes on the server
and rely on the
addslashes() function
to escape user-submitted
text strings.
Figure 4-5
The form string after magic quotes and addslashes()
As of
version 5.3,
magic
quotes are
deprecated
in PHP. As of version 6.0,
they have been removed.
PHP also provides a function to reverse the changes made by magic
quotes or the addslashes() function. The stripslashes() function
removes any slashes that occur before a single quote ('), double quote
("), or NULL character. All other slashes are ignored.

CHAPTER
4
Handling
User Input
To
handle magic quotes in the process_Scholarship.php script:
1.
2.
Reopen
the process_Scholarship.php script in your editor.
Modify
the assignment of the $firstName
and
$lastName
variables
to use the stripslashes()
function
by adding the
code
shown in bold:
<?php
$firstName
= stripslashes($_POST['fName']);
$lastName
= stripslashes($_POST['lName']);
echo
"Thank you for filling out the scholarship form,
".$firstName."
".$lastName . ".";
?>
198
3.
Save the process_Scholarship.php script, upload it to the
server, and then open Scholarship.html in the Web browser
by entering the following URL: http://<yourserver>/
PHP_Projects/Chapter.04/Chapter/Scholarship.html.
Enter a first name or last name that contains an apostrophe to
test if the stripslashes() removed the backslashes inserted
by magic quotes. Figure 4-6 shows the output for the name
“John O’Hara”.
4.
Figure 4-6
The scholarship form after magic quotes are removed
5.
Close the browser window.
Short Quiz
1.
Describe how an autoglobal $_POST array is populated when
the post method is used to submit form data.
Describe the role of magic quotes in working with string data.
What function is used to remove the backslashes added by
magic quotes or the addslashes() function?
2.
3.

Handling
Submitted Form Data
Handling
Submitted Form Data
Once
the data from a Web form is submitted, it needs to be processed
by
the form handler in several steps. First, the form handler needs to
verify
that the entered information is complete, valid, and safe. If the
information
is not complete or valid, the form handler needs to pro-
vide
feedback to the visitor. Next, the form handler needs to prepare
the
submitted data for use. Finally, the form handler needs to use the
submitted
data.
199
Determining
if Form Variables Contain Values
The
first step in validating form data is to determine if fields have
data
entered in them. When form data is posted using the post or get
method,
all controls except unchecked radio buttons and check boxes
get
sent to the server, whether they contain data or not. Because
of
this, simply checking to see if there is an element in the $_POST
or
$_GET
array
is not sufficient to determine if a value was entered.
The
empty()
function
can be used to determine if a variable contains
values.
The empty()
function
returns a value of FALSE
if
the variable
being
checked has a nonempty and nonzero value, and a value of
TRUE
if
the variable has an empty or zero value.
The
empty()
function
returns a
value of
FALSE for a numeric
value of 0. If you are vali-
dating a numeric field for
which 0 is a valid entry,
you must check for a
value of 0 separately.
Validating Entered Data
Often, determining that a value has been entered for a form field is
not sufficient. Some fields require a specific type of data, such as an
integer or a decimal value, or data in a specific format, such as a date
or an e-mail address. Different techniques will help verify that the
value entered in a field is appropriate for the type of data that should
have been entered.
The best way to ensure valid form data is to build the Web form with
controls (such as check boxes, radio buttons, and selection lists)
that only allow the user to select acceptable responses. This method
only works if the user is confined to a predefined set of responses.
However, information such as a user name, password, or e-mail
address is unique for each user. This data needs to be validated to
ensure that the entered values are usable for the type of data required.
Any data
passed to a
form handler
needs to be
validated to
protect against form-
based hacking attempts.
Appendix E contains
details on protecting your
site against these
attacks.
Validating Numeric Data
All data entered in a form is actually string data. PHP automatically
converts string data to numeric data if the string is in numeric for-
mat. The is_*() family of functions can be used to ensure that the
user enters numeric values where necessary. Comparison functions
CHAPTER
4
Handling
User Input
ensure
that values are within a required range. Finally, the round()
function
can be used to ensure that numbers have the appropriate
number
of digits after the decimal point, if any. All of these functions
were
introduced in Chapter 1.
200
For
example, the following function ensures that the entered field,
passed
as the $data
parameter,
is a four-digit year between 1900 and
2100:
function
validateYear($data, $fieldName) {
global
$errorCount;
if (empty($data)) {
echo "<p>The field $fieldName is
required.</p>\n";
++$errorCount;
$retval = "";
} else { // Only clean up the input if it isn't empty
$data = trim($data);
$data = stripslashes($data);
if (is_numeric($data)) {
$data = round($data);
if (($data >= 1900) &&
($data <= 2100)) {
$retval = $data;
} else {
echo "<p>The field $fieldName must be
between 1900 and 2100.</p>\n";
++$errorCount;
$retval = "";
}
} else {
echo "<p>The field $fieldName must be a
number between 1900 and 2100.</p>\n";
++$errorCount;
$retval = "";
}
}
return($retval);
}