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

Including white space,

HTML elements, or output

from the echo or print

statements; otherwise,

you will receive an error.

You can call the setcookie() function multiple times to create addi-

tional cookies—but again, remember that setcookie() statements

must come before any other output on a Web page. The following

example creates three cookies:

setcookie("firstName", "Don");

setcookie("lastName", "Gosselin");

setcookie("occupation", "writer");

PHP also allows you to store cookie values in indexed or associative

arrays by appending array operators ([ ]) and an index or key to the

cookie name within the setcookie() function. The following state-

ments create an indexed cookie array named professional[] that

contains three cookie values:

setcookie("professional[0]", "Don");

setcookie("professional[1]", "Gosselin");

setcookie("professional[2]", "writer");


CHAPTER 9

Managing State Information

The following statements create an associative version of the

professional[] cookie array:

setcookie("professional['firstName']", "Don");

setcookie("professional['lastName']", "Gosselin");

setcookie("professional['occupation']", "writer");

520

By default, cookies cannot include semicolons or other special char-

acters such as commas or spaces, because cookies are transmitted

between Web browsers and Web servers using HTTP, which does not

allow certain nonalphanumeric characters to be transmitted in their

native format. However, you can use special characters in cookies you

create with PHP because the setcookie() function automatically

encodes, or converts, special characters in a text string to their cor-

responding hexadecimal ASCII value, preceded by a percent sign. For

example, 20 is the hexadecimal ASCII equivalent of a space character,

and 25 is the hexadecimal ASCII equivalent of a percent sign (%). In

URL encoded format, each space character is represented by %20, and

each percent sign is represented by %25. After encoding, the contents

of the string "tip=A standard tip is 15%" would read as follows:

tip=A%20standard%20tip%20is%2015%25

Encoding does not occur for standard alphanumeric characters such as

A, B, and C or 1, 2, and 3, or for any of the following special characters:

- _ . ! ~ * ‘ ()

It also does not encode the following characters that have special

meaning in a URL:

; / ? : @ & = + $ ,

For example, the backslash (/) character is not encoded because it

is used for designating a path on a file system. PHP automatically

decodes special characters when you read cookie values. (You will

learn how to read cookies later in this chapter.)

The start of

the opening

PHP tag

must be the

first charac-

ter on the first line of the

file. If anything precedes

the opening PHP tag,

even white spaces or

blank lines, your code will

produce an error.

To modify the New Intern Registration page so that the Intern ID is

stored in a temporary cookie:

1.

Return to the RegisterIntern.php document in your text

editor.

Cut and paste the existing PHP script section above the

<!DOCTYPE> declaration. This is necessary because the

setcookie() function, which you will add later in this

exercise, must be called before any output statements.

Immediately after the opening of the PHP script section, add the

following code to declare and initialize the $Body string variable:

$Body = "";

2.

3.


Using Cookies to Save State Information

4.

Replace each occurrence of the echo statement with the

$Body .= assignment statement. For example, the code:

echo "<p>You need to enter an e-mail

address.</p>\n";

becomes:

$Body .= "<p>You need to enter an e-mail

address.</p>\n";

521

When develop-

ing a PHP

script, you

may acciden-

tally create,

but not delete, persistent

cookies that your pro-

gram does not need.

Unused persistent cook-

ies can sometimes inter-

fere with the execution of

a PHP script, so you may

want to delete your

browser cookies periodi-

cally, especially while

developing a PHP script

that uses cookies. To

delete cookies in Firefox,

click Tools on the menu

bar and select Options. In

the Options dialog box,

click “Use custom set-

tings for history” in the

“Firefox will:” drop-down

box, and then click the

Show Cookies button.

Highlight the desired

cookie and click the

Remove Cookie button,

or click the Remove All

Cookies button to remove

them all. To delete cook-

ies in Microsoft Internet

Explorer, click Tools on

the menu bar and click

Internet Options. Click the

General tab of the

Internet Options dialog

box, and then click the

Delete button in the

Browsing history section.

In the next dialog box,

click the Delete cookies

button.

5.

Add the following setcookie() statement above the

mysql_close() statement at the end of the script section.

This statement creates a new cookie named internID that

contains the newly assigned Intern ID.

setcookie("internID", $InternID);

6.

Within the <body> tags, add the following PHP script to

display the output generated by the previous PHP script:

<?php

echo $Body;

?>

7.

Save the RegisterIntern.php document and upload it to the

Web server.

The expires Argument

For a cookie to persist beyond the current browser session, you

must use the expires argument with the setcookie() function.

You might use a cookie that expires after one week or less to store

data that needs to be maintained for a limited amount of time. For

example, a travel agency may store data in a cookie that temporarily

holds a travel reservation until it expires after one week. Or, an online

retail site may store shopping cart information in cookies that expire

after only 15 minutes. The expires argument determines how long

a cookie can remain on a client system before it is deleted. Cookies

created without an expires argument are available for only the cur-

rent browser session. You assign to the expires argument a value

representing the date or time when the client system is to delete the

cookie. Use PHP’s time() function to return the current time and add

to it an integer in seconds to specify the time to delete the cookie. The

following setcookie() function specifies that the firstName cookie

expires in 3600 seconds, or one hour from now:

setcookie("firstName", "Don", time()+3600);

By multiplying the number of seconds in a minute and an hour, and

then multiplying that value by the necessary number of hours or days,


CHAPTER 9

The following

steps use the

versions of

Firefox and

Internet

Explorer for Windows that

were available when this

book was published.

Different systems and

versions have different

procedures.

Managing State Information

you can specify an expiration time more easily. The following example

specifies that the firstName cookie expires in one week by multiplying

the number of seconds in a minute (60), the number of minutes in an

hour (60), the number of hours in a day (24), and then the number of

days in a week (7).

setcookie("firstName", "Don", time()+(60*60*24*7));

522

To create the Request Opportunity page, which creates a persistent

cookie containing the date of the visitor’s last selection:

1.

Create a new document in your text editor and type the

<!DOCTYPE> declaration, <html> element, header informa-

tion, and <body> element. Use the strict DTD and “Request

Opportunity” as the content of the <title> element.

Add the following text and elements to the document body:

<h1>College Internship</h1>

<h2>Opportunity Requested</h2>

<?php

echo $Body;

?>

The

script

section

will

contain a

setcookie() function,

so be sure to create the

script section above the

opening <!DOCTYPE>

declaration; otherwise,

you will receive an error.

2.

3.

Add a script section above the opening <!DOCTYPE>

declaration:

<?php

?>

4.

Add the following statements to the script section to validate

the submitted data:

$Body = "";

$errors = 0;

$InternID = 0;

if (isset($_GET['internID']))

$InternID = $_GET['internID'];

else {

$Body .= "<p>You have not logged in or

registered. " .

" Please return to the " .

" <a href='InternLogin.

php'>Registration / " .

" Log In page</a>.</p>";

++$errors;

}

if ($errors == 0) {

if (isset($_GET['opportunityID']))

$OpportunityID = $_GET['opportunityID'];

else {

$Body .= "<p>You have not selected an

opportunity. " .

" Please return to the " .

" <a href='AvailableOpportunities.

php?" .


Using Cookies to Save State Information

"internID=$InternID'>Available " .

" Opportunities page</a>.</p>";

++$errors;

}

}

5.

Add the following statements to the end of the script sec-

tion to connect to the database server and open or create the

internships database. Be sure to replace host with the name

of your MySQL server, and user and password with your user

name and password.

if ($errors == 0) {

$DBConnect = @mysql_connect("host", "user",

"password");

if ($DBConnect === FALSE) {

$Body .= "<p>Unable to connect to the

database " .

" server. Error code " . mysql_

errno() . ": " .

mysql_error() . "</p>\n";

++$errors;

}

else {

$DBName = "internships";

$result = @mysql_select_db($DBName,

$DBConnect);

if ($result === FALSE) {

$Body .= "<p>Unable to select the

database. " .

"Error code " . mysql_

errno($DBConnect) .

": " . mysql_error($DBConnect)

. "</p>\n";

++$errors;

}

}

}

523

6.

Add the following statements to the end of the script

section to mark the opportunity as selected in the

assigned_opportunities table and close the database con-

nection. The date() function is used to return the current

date and time as a formatted string. For the $DisplayDate

variable, the format string "l, F j, Y, g:i A" creates a

date string in a user-friendly format; the day of the week, the

month name, and the day and year are followed by the time as

hours and minutes AM or PM. For the $DatabaseDate vari-

able, the format string "Y-m-d H:i:s" creates a date string

in the format MySQL uses: “yyyy-mo-dd hh:mi:ss”, where

yyyy is a four-digit year, mo is a two-digit month, dd is a two-

digit day of the month, hh is a two-digit number indicating


CHAPTER 9

Managing State Information

the hours since midnight, mi is a two-digit minute, and ss is a

two-digit second.

$DisplayDate = date("l, F j, Y, g:i A");

$DatabaseDate = date("Y-m-d H:i:s");

if ($errors == 0) {

$TableName = "assigned_opportunities";

$SQLstring = "INSERT INTO $TableName " .

" (opportunityID, internID, " .

" date_selected) VALUES " .

" ($OpportunityID, $InternID, " .

" '$DatabaseDate')";

$QueryResult = @mysql_query($SQLstring,

$DBConnect) ;

if ($QueryResult === FALSE) {

$Body .= "<p>Unable to execute the query. " .

" Error code " . mysql_

errno($DBConnect) .

": " . mysql_error($DBConnect) .

"</p>\n";

++$errors;

}

else {

$Body .= "<p>Your request for opportunity

# " .

" $OpportunityID has been

entered " .

" on $DisplayDate.</p>\n";

}

mysql_close($DBConnect);

}

524

7.

Add the following statements to the end of the script section

to provide a link back to the Available Opportunities page if

the Intern ID is valid, or to the Registration/Log In page if the

Intern ID is not valid.

if ($InternID > 0)

$Body .= "<p>Return to the <a href='" .

"AvailableOpportunities.

php?internID=$InternID'>" .

"Available Opportunities</a> page.</p>\n";

else

$Body .= "<p>Please <a href='InternLogin.

php'>Register " .

" or Log In</a> to use this page.</p>\n";

8.

Add the following statements to the end of the script section

to create a persistent cookie named LastRequestDate. The

urlencode() function is used because of the special charac-

ters needed for the date and time. The cookie is set to expire

one week from now.


Using Cookies to Save State Information

if ($errors == 0)

setcookie("LastRequestDate",

urlencode($DisplayDate),

time()+60*60*24*7);

9.

Save the document as RequestOpportunity.php in the

Chapter directory for Chapter 9 and upload the file to the

Web server.

525

The path Argument

The path argument determines the availability of a cookie to other

Web pages on a server. By default, a cookie is available to all Web

pages in the same directory. However, if you specify a path, a cookie is

available to all Web pages in the specified path and in all its subdirec-

tories. For example, the following statement makes the cookie named

firstName available to all Web pages located in the marketing direc-

tory or any of its subdirectories:

setcookie("firstName", "Don", time()+3600, "/marketing/");

To make a cookie available to all directories on a server, use a forward

slash (/) to indicate the root directory:

setcookie("firstName", "Don", time()+3600, "/");

Many different types of Web applications use the same cookie name,

such as username or id. This can cause conflicts if both Web applica-

tions are on the same Web site. Therefore, you should always place

PHP applications that use cookies into their own directory and use

the path argument to specify the directory for that application. This

approach will prevent different applications from changing the same

cookie, which would result in erratic behavior for the scripts.

If you use a

/develop-

ment

directory

when develop-

ing cookie-based PHP

applications, and place

each application in its

own subdirectory of the

/development direc-

tory, you will help avoid

conflicts not only between

PHP applications in devel-

opment, but with other

PHP applications that are

already installed.

The domain Argument

Using the path argument allows cookies to be shared across a

server. Some Web sites, however, are very large and use a num-

ber of servers. The domain argument is used for sharing cookies

across multiple servers in the same domain. Note that you cannot

share cookies outside of a domain. For example, if the Web server

programming.gosselin.com needs to share cookies with the Web

server writing.gosselin.com, the domain argument for cookies set

by programming.gosselin.com should be set to .gosselin.com.

That way, cookies created by programming.gosselin.com are avail-

able to writing.gosselin.com and to all other servers in the domain

gosselin.com.


CHAPTER 9

Managing State Information

The following code shows how to make a cookie at

programming.gosselin.com available to all servers in the

gosselin.com domain:

setcookie("firstName", "Don", time()+3600, "/",

".gosselin.com");

526

The secure Argument

Internet connections are not always considered safe for transmitting

sensitive information. Unscrupulous people can steal personal infor-

mation online, such as credit card numbers, passwords, and Social

Security numbers. To protect private data transferred across the

Internet, Netscape Communications developed Secure Sockets Layer,

or SSL, to encrypt and transfer data across a secure connection. URLs

for Web pages that support SSL usually start with https: instead

of http:. The secure argument indicates that a cookie can only be

transmitted across a secure Internet connection using HTTPS or

another security protocol. To use this argument, you assign a value of

1 (for TRUE) or 0 (for FALSE) as the last argument of the setcookie()

function. For example, to specify the secure attribute for a cookie,

you use a statement similar to the following:

Elements

of the

$_COOKIE[]

autoglobal

array are

also automatically

assigned to the

$_REQUEST[] auto-

global array, along with

all of the elements of the

$_POST[] and

$_GET[] autoglobal

arrays.

setcookie("firstName", "Don", time()+3600, "/",

".gosselin.com", 1);

Reading Cookies

Cookies that are available to the current Web page are automati-

cally assigned to the $_COOKIE[] PHP autoglobal array. You can then

access each cookie by using the cookie name as a key in the associa-

tive $_COOKIE[] array. (Recall that autoglobals are associative arrays.)

The following statement displays the value assigned to the firstName

cookie:

echo $_COOKIE['firstName'];

When you create a cookie with the setcookie() function, the cookie

is not available to the current Web page until you reload it. For

example, the following statement causes an error when the Web page

first loads because you cannot access the firstName, lastName, and

occupation cookies until you reload the Web page:

setcookie("firstName", "Don");

setcookie("lastName", "Gosselin");

setcookie("occupation", "writer");

echo "{$_COOKIE['firstName']} {$_COOKIE['lastName']} is a

{$_COOKIE['occupation']}.";


Using Cookies to Save State Information

To ensure that a cookie is set before you attempt to use it, you can

use the isset() function, the same as when you check whether form

variables contain values.

setcookie("firstName", "Don");

setcookie("lastName", "Gosselin");

setcookie("occupation", "writer");

if (isset($_COOKIE['firstName'])

&& isset($_COOKIE['lastName'])

&& isset($_COOKIE['occupation']))

echo "{$_COOKIE['firstName']} {$_COOKIE['lastName']}

is a {$_COOKIE['occupation']}.";

527

When you store cookies in indexed or associative arrays, PHP

stores the cookies as two-dimensional arrays within the $_COOKIE[]

autoglobal. Therefore, you must use multidimensional array syntax

to read each cookie value. You refer to cookie arrays by using the

cookie name as the first dimension and each index or key that rep-

resents a cookie value as the second dimension. For example, the

following statements create and display an indexed version of the

professional[] cookie array:

setcookie("professional[0]", "Don");

setcookie("professional[1]", "Gosselin");

setcookie("professional[2]", "writer");

if (isset($_COOKIE['professional']))

echo "{$_COOKIE['professional'][0]}

{$_COOKIE['professional'][1]} is a

{$_COOKIE['professional'][2]}.";

The following statements create and display an associative version of

the professional[] cookie array:

setcookie("professional[firstName]", "Don");

setcookie("professional[lastName]", "Gosselin");

setcookie("professional[occupation]", "writer");

if (isset($_COOKIE['professional']))

echo "{$_COOKIE['professional']['firstName']}

{$_COOKIE['professional']['lastName']} is a

{$_COOKIE['professional']['occupation']}.";

To modify the Available Opportunities page so that it reads the stored

LastRequestDate cookie:

1.

Return to the AvailableOpportunities.php document in

your text editor.

Add the following statements, which read the

LastRequestDate cookie from the $_COOKIE[] autoglobal

array, immediately after the statement that retrieves the

Intern ID from the $_REQUEST[] autoglobal array. You need

both sets of code because the Registration/Log In page still

uses a query string to log in existing users.

2.


CHAPTER 9

Managing State Information

if (isset($_COOKIE['LastRequestDate']))

$LastRequestDate = $_COOKIE['LastRequestDate'];

else

$LastRequestDate = "";

3.

528

Add the following statements above the statements that dis-

play the table of opportunities. This code displays the value of

the LastRequestDate cookie if it is set.

if (!empty($LastRequestDate))

echo "<p>You last requested an internship

opportunity " .

" on $LastRequestDate.</p>\n";

4.

Save the AvailableOpportunities.php document and upload it

to the Web server.

Open the InternLogin.php file in your Web browser by

entering the following URL: http://<yourserver>/PHP_

Projects/Chapter.09/Chapter/InternLogin.php. In the Return-

ing Intern Login form, enter the e-mail address and password

that you registered with the New Intern Registration form

and click the Log In button. You should see the same “Wel-

come Back” Web page.

Click the Available Opportunities link to open the Avail-

able Opportunities page. The page should open just as it did

before.

Click the Available link in the Status column of one of the

opportunities to open the Request Opportunity page. You

should see an acknowledgement message like the one shown

in Figure 9-8.

5.

6.

7.

Figure 9-8

Request Opportunity Web page displaying a successful request

8.

Click the Available Opportunities link to open the Available

Opportunities page. The page should now show the oppor-

tunity as “Selected” and should display the time of your last


Using Cookies to Save State Information

selection above the table. Figure 9-9 shows that Opportunity 1

was selected.

529

Figure 9-9

9.

Available Opportunities Web page displaying text from a persistent cookie

Close your Web browser window.

Deleting Cookies

You do not need to delete temporary cookies because they automati-

cally cease to exist when the current browser session ends. Persistent

cookies are also automatically deleted when the time assigned to

the setcookie() function’s expires argument elapses. To delete a

persistent cookie before the time assigned to the expires argument

elapses, set the value to an empty string and assign a new expiration

value to a time in the past. You do this by subtracting any number of

seconds from the time() function. The following statements delete

the firstName, lastName, and occupation cookies by subtracting 3600

seconds (one hour) from the current time:

setcookie("firstName", "", time()−3600);

setcookie("lastName", "", time()−3600);

setcookie("occupation", "", time()−3600);

If you do not

set the value

to an empty

string, the

old value will

persist until you close the

Web browser.


CHAPTER 9

Managing State Information

Short Quiz

1.

530

Detail the differences between temporary cookies and persis-

tent cookies.

Describe three limitations of cookies.

Explain why the setcookie() function must be called before

any output is sent to the browser.

Why is it important to set the expiration date of a cookie in

a script when you might want to greet the user by name the

next time he or she visits the Web?

What is the purpose of the domain argument?

2.

3.

4.

5.

Using Sessions to Save State

Information

Many clients

do not

accept cook-

ies due to

the rampant

rise of spyware, which is

malicious software that

gathers user information

from a local computer for

marketing and advertising

purposes without the

user’s knowledge. Users

increasingly choose to

disable cookies to pre-

vent spyware from gath-

ering user information

from stored cookies.

Cookies are a common state preservation technique used by various

Web development tools in addition to PHP. However, several security

issues are involved with saving state in cookies on a client computer.

First, you cannot ensure the security of every client computer on

which your PHP scripts will run. This means that any private infor-

mation stored in cookies, including Social Security numbers and

credit card information, may be accessible by hackers. Because of

these risks, many clients configure their Web browsers not to accept

cookies. (You can disable cookies in every current Web browser.)

Unfortunately, this also disables any cookie preservation code in your

PHP scripts.

PHP offers a more secure alternative to cookies: storing state infor-

mation in sessions. The term session refers to a period of activity

when a PHP script stores state information on a Web server. A ses-

sion is similar to a temporary cookie in that it is only available for the

current browser session. If you want to store state information that

will be available when a client revisits your Web site in the future, you

must use cookies. Sessions are a little harder to use than cookies, but

because sessions store state information on a Web server rather than

on the user’s computer, they are much safer to use—provided you

properly secure your Web server. Another benefit to using sessions is

that they allow you to maintain state information even when clients

disable cookies in their Web browsers.

The php.ini

configuration

file contains

numerous

directives that

you can use to control

how sessions behave in

your environment.


Using Sessions to Save State Information

Starting a Session

Whenever you need to work with sessions in a PHP script, you

must call the session_start() function, which starts a new ses-

sion or continues an existing one. When you start a new session, the

session_start() function generates a unique session ID to identify

the session. A session ID is a random alphanumeric string that looks

something like 7f39d7dd020773f115d753c71290e11f. In addition to

generating a session ID, the session_start() function creates a text

file on the Web server that has the same name as the session ID, pre-

ceded by sess_. For example, the session ID text file for the preceding

session ID would be named sess_7f39d7dd020773f115d753c71290

e11f. Any variables that are generated for a session are stored on the

Web server in this text file.

Session ID text files are stored in the Web server directory specified

by the session.save_path directive in your php.ini configuration file.

The session_start() function does not accept any arguments,

nor does it return a value that you can use in your script. Instead,

you simply call the session_start() function by itself in your PHP

script, as follows:

<?php

session_start();

...

531

Like the setcookie() function, you must call the session_start()

function before you send the Web browser any output, including

white space, HTML elements, or output from the echo or print state-

ments. If any output exists before you call the session_start() func-

tion, you receive an error and the function returns a value of FALSE.

If a client’s Web browser is configured to accept cookies, the session

ID is assigned to a temporary cookie named PHPSESSID. However,

because you cannot be certain that every client accepts cookies, you

should also pass the session ID as a query string or hidden form field

to any Web pages that are called as part of the current session. You

pass a session ID in a name/value pair of PHPSESSID=session ID. You

use the session_id() function to retrieve the session ID for the cur-

rent session. For example, the following code starts a session and uses

the session_id() function to pass the session ID as a query string to

a Web page named Occupation.php:

<?php

session_start();

...

?>

<p><a href='<?php echo "Occupation.php?PHPSESSID="

. session_id() ?>'>Occupation</a></p>


CHAPTER 9

The SID

constant

may or may

not be

defined on

your system. It is enabled

through a configuration

setting in the php.ini file.

If SID is not enabled on

your system, use

PHPSESSID as the name

and the return value of

the session_id()

function as the value

instead.

Managing State Information

You can also use the constant SID, which contains a string that con-

sists of "PHPSESSID=" and the session ID. The following example

demonstrates how to use the constant SID to pass the session ID as a

query string to another page:

<?php

session_start();

...

?>

<p><a href='<?php echo "Occupation.php?"

. SID ?>'>Occupation</a></p>

532

For hidden form fields, assign a value of PHPSESSID to the name attri-

bute and use the session_id() function to assign the session ID to

the value attribute of the <input> element, as follows:

<input type="hidden" name="PHPSESSID"

value='<?php echo session_id() ?>' />

To modify the Registration/Log In page so that it uses a session that

tracks the Intern ID number of the current user:

1.

2.

Return to the InternLogin.php document in your text editor.

Insert the following PHP script section above the opening

<!DOCTYPE> declaration:

<?php

?>

3.

Add the following session_start() statement to the begin-

ning of the script section:

session_start();

4.

Modify the action attribute of the two forms so they pass the

session ID in a query string. The modified links should appear

as follows:

<form method="post"

echo SID;

...

<form method="post"

echo SID;

action="RegisterIntern.php?<?php

?>">

action="VerifyLogin.php?<?php

?>">

5.

Save the InternLogin.php document and upload it to the Web

server.

Working with Session Variables

You store session state information in the $_SESSION[] autoglobal.

When you call the session_start() function, PHP either initializes a

new $_SESSION[] autoglobal or retrieves any variables for the current

session (based on the session ID) into the $_SESSION[] autoglobal.


Using Sessions to Save State Information

For example, the following code declares and initializes three vari-

ables—firstName, lastName, and occupation—in the $_SESSION[]

autoglobal:

<?php

session_start();

$_SESSION['firstName'] = "Don";

$_SESSION['lastName'] = "Gosselin";

$_SESSION['occupation'] = "writer";

?>

<p><a href='<?php echo "Occupation.php?"

. session_id() ?>'>Occupation</a></p>

533

When a user clicks the Occupation link, the firstName, lastName, and

occupation variables are available in the $_SESSION[] autoglobal on

the Occupation.html page. If the Occupation.html page contains the

following script section, it displays Don Gosselin is a writer :

<?php

session_start();

echo "<p>" . $_SESSION['firstName'] . " " .

$_SESSION['lastName']

. " is a " . $_SESSION['occupation'] . "</p>\n";

?>

As with cookies, you can use the isset() function to ensure that a

session variable is set before you attempt to use it, as follows:

<?php

session_start();

if (isset($_SESSION['firstName']) &&

isset($_SESSION['lastName']) &&

isset($_SESSION['occupation']))

echo "<p>" . $_SESSION['firstName'] . " "

. $_SESSION['lastName'] . " is a "

. $_SESSION['occupation'] . "</p>\n";

?>

To modify the New Intern Registration page so that it stores the

Intern ID number in the $_SESSION[] autoglobal:

1.

Return to the RegisterIntern.php document in your text

editor.

Add a session_start() statement to the beginning of the

script section:

session_start();

2.

3.

Locate the statement at the end of the script section that

declares the $InternID variable and modify it so the ID

returned from the mysql_insert_id() function is assigned to

the $_SESSION[] autoglobal, as follows:

$_SESSION['internID'] = mysql_insert_id($DBConnect);


CHAPTER 9

Managing State Information

4.

Modify the paragraph element in the document body that dis-

plays the Intern ID so it refers to the $_SESSION['internID']

autoglobal variable instead of the $InternID variable, as

follows:

$Body .= "Your new Intern ID is <strong>" .

$_SESSION['internID'] . "</strong>.</p>\n";

534

5.

Replace the code that uses the hidden input in a form with a

link that uses the session ID, as follows:

$Body .= "<p><a href='AvailableOpportunities.php?" .

SID . "'>View Available Opportunities</a></p>\n";

6.

Save the RegisterIntern.php document and upload it to the

Web server.

To modify the Verify Login page so that it stores the Intern ID num-

ber in the $_SESSION[] autoglobal:

1.

2.

Return to the VerifyLogin.php document in your text editor.

Add a PHP script section with a session_start() statement

before the <!DOCTYPE> tag:

<?php

session_start();

?>

3.

Locate the statement at the end of the script section that

declares the $InternID variable and modify it so the

ID returned from the database query is assigned to the

$_SESSION[] autoglobal, as follows:

$_SESSION['internID'] = $Row['internID'];

4.

Replace the code that creates a link that passes the Intern ID

with a link that passes the session ID, as follows:

echo "<p><a href='AvailableOpportunities.php?" .

SID . "'>Available Opportunities</a></p>\n";

5.

Save the VerifyLogin.php document and upload it to the Web

server.

To modify the Available Opportunities page so that it uses the Intern

ID number from the $_SESSION[] autoglobal:

1.

Return to the AvailableOpportunities.php document in

your text editor.

Add a PHP script section with a session_start() statement

before the <!DOCTYPE> tag:

<?php

session_start();

?>

2.


Using Sessions to Save State Information

3.

Remove the following code that uses the

$_REQUEST['internID'] element:

if (isset($_REQUEST['internID']))

$InternID = $_REQUEST['internID'];

else

$InternID = −1;

535

4.

Modify the three queries that use $InternID so that they use

$_SESSION['internID'] instead, as follows:

$SQLstring = "SELECT * FROM $TableName WHERE " .

" internID='" . $_SESSION['internID] . "'";

...

$SQLstring = "SELECT COUNT(opportunityID) FROM

$TableName " .

" WHERE internID='" . $_SESSION['internID'] . "' " .

" AND date_approved IS NOT NULL";

...

$SQLstring = "SELECT opportunityID FROM $TableName " .

" WHERE internID='" . $_SESSION['internID'] . "'";

5.

Modify the link to RequestOpportunity.php to use the session

ID instead of the Intern ID, as follows:

echo "<a href='RequestOpportunity.php?" .

SID . "&opportunityID=" .

$Opportunity['opportunityID'] .

"'>Available</a>";

6.

Save the AvailableOpportunities.php document and upload it

to the Web server.

To modify the RequestOpportunity.php document so that it uses the

session ID to retrieve user information:

1.

Return to the RequestOpportunity.php document in your

text editor.

Add the following statement to the beginning of the script

section to start the session:

session_start();

2.

3.

Remove the following section that checks the

$_GET['internID'] autoglobal:

if (isset($_GET['internID']))

$InternID = $_GET['internID'];

else {

and replace it with the following if statement that checks the

$_SESSION['internID'] autoglobal:

if (!isset($_SESSION['internID'])) {


CHAPTER 9

Managing State Information

4.

In both sections of code that link to the AvailableOpportu-

nities.php page, replace the Intern ID in the link so that the

session ID is passed instead, as follows:

$Body .= "<p>You have not selected an

opportunity. " .

" Please return to the " .

" <a href='AvailableOpportunities.

php?" .

SID . "'>Available " .

" Opportunities page</a>.</p>";

...

$Body .= "<p>Return to the <a href='" .

"AvailableOpportunities.php?" . SID .

"'>" .

"Available Opportunities</a> page.

</p>\n";

536

5.

Modify the insert query string so it refers to the

$_SESSION['internID'] autoglobal variable instead of the

$InternID variable, as follows:

$SQLstring = "INSERT INTO $TableName " .

" (opportunityID, internID, " .

" date_selected) VALUES " .

" ($OpportunityID, " .

$_SESSION['internID']

. ", '$DatabaseDate')";

6.

Locate the if statement that checks if $InternID is greater

than 0, and modify it to refer to the $_SESSION['internID']

autoglobal variable instead, as follows:

if ($_SESSION['internID'] > 0)

7.

Save the RequestOpportunity.php document and upload it to

the Web server.

Deleting a Session

Although a session automatically ends when the current browser

session ends, sometimes you need to delete a session manually. For

example, you might want to give users the opportunity to end a ses-

sion by clicking a Log Out button or link, or you might want a session

to end if it is inactive for a specified period of time. To delete a ses-

sion, you must perform the following steps:

1.

Execute the session_start() function. (Remember that you

must call the session_start() function whenever you need

to work with sessions in a PHP script.)


Using Sessions to Save State Information

2.

Use the array() construct to reinitialize the $_SESSION[]

autoglobal.

Use the session_destroy() function to delete the session.

3.

For example, the following code deletes a session:

<?php

session_start();

$_SESSION = array();

session_destroy();

?>

537

To modify the Registration/Log In page so that it deletes any existing

sessions whenever a user opens it:

1.

2.

Return to the InternLogin.php document in your text editor.

Add the following code immediately after the

session_start() function in the PHP script section:

$_SESSION = array();

session_destroy();

3.

Save the InternLogin.php document and upload it to the Web

server.

Open the InternLogin.php file in your Web browser by enter-

ing the following URL: http://<yourserver>/PHP_Projects/

Chapter.09/Chapter/InternLogin.php. Enter the e-mail

address and password for a registered user and click the Log

In button. You should see the Login Successful page. Click the

Available Opportunities link to open the Available Oppor-

tunities page. Notice the session ID appended to the URL in

your browser’s address box.

Click the Log Out link on the Available Opportunities page to

execute the session deletion code.

Close your Web browser window.

4.

5.

6.

Short Quiz

1.

Describe two problems with cookies that do not affect

sessions.

Explain the purpose of the temporary cookie named

PHPSESSID.

How does the constant SID pass the session ID as a query

string to another page?

2.

3.

CHAPTER 9

Managing State Information

4.

What function is used to ensure that the session variable is set

before you attempt to use it?

What function must be used when a visitor uses a Log Out

button to end a session?

5.

538

Summing Up

• Information about individual visits to a Web site is called state

information. Maintaining state means to store persistent informa-

tion about Web site visits.

• To pass form values from one PHP script to another, you can store

the values in hidden form fields, which are submitted along with

other types of form fields.

• One way to preserve information following a user’s visit to a Web

page is to append a query string to the end of a URL. To pass infor-

mation from one Web page to another using a query string, add a

question mark (?) immediately after a URL, followed by the query

string containing the information you want to preserve in name/

value pairs.

• Cookies, also called magic cookies, are small pieces of informa-

tion about a user that are stored by a Web server in text files on

the user’s computer. Cookies can be temporary or persistent.

Temporary cookies remain available only for the current browser

session. Persistent cookies remain available beyond the current

browser session and are stored in a text file on a client computer.

• You use the

setcookie() function to create cookies in PHP. You

must call the setcookie() function before you send the Web

browser any output, including white space, HTML elements, or

output from the echo or print statements.

• Cookies created with only the

name and value arguments of the

setcookie() function are temporary cookies, because they are

available for only the current browser session.

• For a cookie to persist beyond the current browser session, you

must use the expires argument with the setcookie() function.

• The

path argument of the setcookie() function determines the

availability of a cookie to other Web pages on a server.


Comprehension Check

• The

secure argument of the setcookie() function indicates that a

cookie can only be transmitted across a secure Internet connection

using HTTPS or another security protocol.

• To delete a persistent cookie before the time elapses in the

assigned expires argument, assign a new expiration value to a

time in the past and clear the value. You do this by subtracting any

number of seconds from the time() function and setting the value

of the cookie to the empty string.

• Sessions refer to periods of activity when a PHP script stores state

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