Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
PHP Programming With MySQL Second Edition.doc
Скачиваний:
0
Добавлен:
01.05.2025
Размер:
43.07 Mб
Скачать

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

Is submitted using the “post” method, the form data is embedded in

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 (+),

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 the

submit 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);

}

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]