Tải bản đầy đủ (.pdf) (50 trang)

Tài liệu PHP and MySQL by Example- P14 pptx

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (1.88 MB, 50 trang )

}
?>
</font>
</body>
</html>
Explanation
"
#$%!&'()*!+,,-'%!-%./0123%!41'(!')!)%*5!#$%!617%!,&!*$%!+,,-'%!')!"usr"!168!*$%!
+,((%)4,68'69!0123%!')!"Ellie Quigley"5
:
#$%!)%+,68!+,,-'%!-%./0123%!41'(!')!)%*5!#$%!617%!,&!*$%!+,,-'%!')!"color"!168!*$%!
+,((%)4,68'69!0123%!')!"blue"5!;,(7122.<!*$%!3)%(!=,328!4(,0'8%!*$%!0123%!&(,7!1!
&,(75
>
?%+13)%!+,,-'%)!='22!6,*!@%+,7%!0')'@2%!36*'2!*$%!6%A*!2,18'69!,&!*$%!419%!=$%(%!*$%!
+,,-'%!)$,328!@%!0')'@2%<!.,3!+16!*%)*!'&!1!+,,-'%!=1)!)3++%))&322.!)%*!@%&,(%!%A*(1+*'69!
'*)!+,6*%6*)5!B%%!C'93(%!"D5>5
E
#$%!print_r!&36+*',6!8')421.)!*$%!+,6*%6*)!,&!*$%!+,,-'%5!F&!*$%!+,,-'%!$18!6,*!@%%6!
)%*!,(!$18!%A4'(%8!*$%(%!=,328!@%!6,!,3*43*!G)%%!C'93(%!"D5:H5!I22!*$%!,*$%(!1**('@3*%)!
)%*!&,(!*$%!+,,-'%<!2'-%!%A4'(1*',6!81*%<!41* $<! )%+3('*.<!168!),!,6<!1(%!6,*!0')'@2%5
!
Figure 16.2. The first time the page is viewed the $_COOKIE array is empty.



Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Figure 16.3. When the page is refreshed, the $_COOKIE array has cookie values.

!
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.


Figure 16.4. The browser sends the cookie back to the server; the server sets the cookie in a header. See Figure
16.5, a diagram illustrating server/browser/PHP interaction with cookies.
!
!
Figure 16.5. The cookie is sent in an HTTP header.
!
!
!


Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Storing Multiple Values in One Cookie—Serialization
The setcookie() function accepts one string as its value. In the previous example, the setcookie() function
was called twice to register two cookie values. Because the number of cookies is limited to 20 per domain, you might
want to assign multiple values to one cookie, for example, data coming in from a form. In the following example, one
cookie will store three values. This example demonstrates how to serialize data. Serializing the data allows you to
convert an array into a string that will be accepted by the cookie. After retrieving the cookie contents, you will have to
unserialize it to convert the string back to an array.
The PHP serialize() function returns a string containing a byte-stream representation of the value, making the
value acceptable for storage anywhere—in this example, a cookie, though serialization is also used for storing variables
and objects in a file or database. (If you go to your browser and look at the actual data stored in the cookie, it has been
URL-encoded.)
Use unserialize() to return the string to its orginal form.
Example 16.2.
J,8%!K'%=L!
<?php
1 $info = array("ellie", "yellow", 22);
2 setcookie("usr", serialize($info));
?>
<html><head><title>Multiple Cookie Values</title></head>

<html><head><title>The Cookie Array?</title></head>
<body bgcolor="lavender">
<font face="verdana" size='+1'>
<h2>$_COOKIE[]</h2>
<pre>
<b>
<?php
3 if(! empty($_COOKIE['usr'])){
4 $cookie_data= $_COOKIE['usr'];
5 $cookie_data=stripslashes($cookie_data);
6 $cookie_data=unserialize("$cookie_data");
echo "What's in the cookie array< br />";
7 print_r($_COOKIE);
echo "<pre>Unserialized data< br />";
8 print_r( $cookie_data);
}
?>

</b>
</pre>
</font>
</body>
Explanation
"
#$%!1((1.!')!1))'96%8!1!2')*!,&!0123%)5
:
#$%!setcookie()!&36+*',6!')!9'0%6!*$%!617%!,&!*$%!+,,-'%!&,22,=%8!@.!*$%!0123%5!#$%!
0123%!')!16!1((1.!*$1*!')!)%('12'M%8!'6*,!,6%!)*('695!#$%!6%=!)*('69!='22!@%!'6!1!&,(71*!*$1*!
')!1++%4*1@2%!&,(!16.!*.4%!,&!)*,(19%5!F*!(%4(%)%6*)!*$%!81*1!*.4%!168!637@%(!,&!
+$1(1+*%()!'6!*$%!,('9'612!81*15!a:3!7%16)!1!*$(%%N%2%7%6*!1((1.<!s:5!1!ON+$1(1+*%(!

)*('69<!168!),!,6<!1)!)$,=6!'6!*$%!,3*43*!,&!*$')!4(,9(175!?.!)%('12'M'69!*$%!1((1.!'6*,!
,6%!)*('69<!=%!,62.!6%%8!*,!+122!setcookie()!,6+%5
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
,6%!)*('69<!=%!,62.!6%%8!*,!+122!setcookie()!,6+%5
>
J$%+-!*,!)%%!'&!*$%!+,,-'%!$1)!16.!0123%<!* $1*!')<!'&!'*!=1)!)%*5
E
#$%!+,,-'%!81*1!')!(%*('%0%8!&,(!*$%!3)%(!168!1))'96%8!*,!$cookie_data5!F*!')!1!)%('12'M%8!
)*('695!B%%!C'93(%!"D5D5
O
#$%!)21)$%)!1(%!)*('44%8!&(,7!*$%!)*('695!F&!.,3!8,!6,*!(%7,0%!*$%!@1+-)21)$%)<!*$%!
unserialize()!&36+*',6!,6!*$%!6%A*!2'6%!&1'2)5
D
#$%!unserialize()!&36+*',6!(%*3(6)!*$%!,('9'612!1((1.5
P
Q,3!+16!)%%!'6!*$%!0123%!,&!*$%!+,,-'%!*$%!)%('12'M%8!1((1.5
R
#$%!36)%('12'M%8!1((1.!')!4('6*%85!S%!6,=!$10%!*$%!,('9'612!0123%)!@1+-5!B%%!C'93(%!"D5D5
!
Figure 16.6. Storing an array in a single cookie.
!
!
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
16.3.2. Tracking Visitors with Cookies
The following examples demonstrate the use of cookies for tracking vistitor activities, such as when the visitor last
viewed the page and how many times he or she has been there, but they can also be used to check user preferences, user
IDs, and so on. Cookies are useful for retaining small amounts of information, but not all browsers support cookies and
if they are supported, a user can turn them off. To overcome these problems, a better solution is to use PHP sessions
(discussed in “What Is a Session?” on page 694 of this chapter).
Visitor Count Example

The following example uses a cookie to count the number of times the user has visited this page. Once the cookie is set,
its value will be increased by 1 each time the visitor comes back to the page.
Example 16.3.
<?php
1 $count = $_COOKIE['visits']; // Accessing the cookie value

2 if( $count == ""){
3 $count = 1; // Initialize the counter
}
else{
4 $count++;
}
5 setcookie("visits",$count); // "visits" is the cookie name
?>
<html><head><title>Setting Cookies</title></head>
<body bgcolor="lavender">
<font size=+1 face="arial">
<h2>Visitor Count with Cookies</h2>
You are visitor number <?php echo $count; ?>.<br />
</font>
</body>
</html>
Explanation
"
#$%!0123%!)*,(%8!'6!*$%!$_COOKIE!1((1.!')!%A*(1+*%8!168!1))'96%8!*,!$count5!
#$%!0123%!')!T3)*!16!'6*%9%(!*$1*!+,6*'63%)!*,!@%!'6+(%7%6*%8!@.!"!%1+$!*'7%!
*$%!3)%(!(%2,18)!*$%!419%5!F&!*$')!')!*$%!&'()*!*'7%!*$%!419%!$1)!@%%6!2,18%8<!*$%!
$_COOKIE!1((1.!='22!@%!%74*.5
:<!
>

F&!*$')!')!*$%!&'()*!*'7%!*$%!3)%(!$1)!0')'*%8!*$')!419%<!$count!='22!@%!%74*.<!168!
'*!='22!@%!)%*!*,!"5!B%%!C'93(%!"D5P5
E
C,(!%1+$!)3@)%U3%6*!0')'*!*,!*$')!419%<!* $%! 0123%!,&!*$%!+,36*%(!='22!@%!
'6+(%1)%8!@.!"5!B%%!C'93(%!"D5R5
O
#$%!setcookie()!&36+*',6!)%*)!*$%!+,,-'%!=$%6!*$%!419%!')!&'()*!2,18%85!#$%!
617%!,&!*$%!+,,-'%!')!visits!168!*$%!0123%!)*,(%8!*$%(%!='22!@%!'6+(%7%6*%8!
@.!"!%1+$!*'7%!*$%!419%!')!(%0')'*%85!#$%!+,,-'%!')!)*,(%8!,6!*$%!3)%(V)!
@(,=)%(!168!='22!@%!8%2%*%8!=$%6!*$%!@(,=)%(!')!%A'*%85!S$1*!')!'74,(*16*!*,!
6,*%!$%(%!')!*$1*!*$%!+,,-'%!')!)%6*!'6!1!$%18%(<!168!$%18%()!73)*!@%!)%6*!
@%&,(%!16.!,*$%(!,3*43*!&(,7!*$')!419%5!#$%!W#XY!,3*43*!')!421+%8!1&*%(!*$')!
2'6%!,(!ZWZ!='22!)%68!=1(6'69)!*,!*$%!)+(%%65
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Figure 16.7. Cookies used to count visitors.

!
Figure 16.8. The cookie value is incremented each time the page is reloaded.



Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Tracking the Visitor’s Last Visit
The following example keeps track of when a visitor last viewed the page. The cookie will store the current date, which
will be retrieved the next time the page is refreshed.
Example 16.4.
J,8%!K'%=L!
(Page 1 The HTML page)

<html><head><title>Setting Cookies</title></head>

<body bgcolor="lavender">
<font size=+1 face="arial">
<h2>Tracking Visitors with Cookies</h2>
<H1>Welcome to our Site!</H1>
<p>
1 Check out our product line
<a href="http://localhost/exemples/sessions/message.php">
Click here</a>
</font>
</body>
</html>

(Page 2 The PHP Script Set a Cookie)

<?php
// Filename: "message.php"
2 $date_str="l dS \of F Y h:i:s A";
$last_visit="Your last visit was on ". date("$date_str");
3 setcookie("message","$last_visit");
?>
<html><head><title>Products</title>
</head>
<body bgcolor="lavender">
<font face="verdana" size='+1'>
<h2>Products Page</h2>
<! Rest of page goes here >
<?php
4 if(! empty($_COOKIE['message'])){ // Has the cookie been
set?
5 $when="$_COOKIE[message]";

echo $when,".< br />";
}
?>
</font></body></html>
Explanation
"
S$%6!*$%!3)%(!+2'+-)!,6!*$%!2'6-!'6!*$')!W#XY!&,(7<!$%!,(!)$%!='22!@%!8'(%+*%8!*,!*$%!
419%!G419%!:H!*$1*!+,6*1'6)!*$%!+,8%!&,(!)%**'69!1!+,,-'%5!#$%!'6'*'12!&,(7!')!)$,=6!'6!
C'93(%!"D5[5
:
I&*%(!+2'+-'69!*$%!2'6-!GC'93(%!"D5[H!'6!419%!"<!*$%!3)%(!')!8'(%+*%8!*,!419%!:<!*$%!
\Z(,83+*)!Z19%]!GC'93(%!"D5"^H5!#$%!01('1@2%!')!1))'96%8!1!)*('69!,&!1(937%6*)!*$1*!='22!
@%!)%6*!*,!*$%!ZWZ!date()!&36+*',6!,6!*$%!6%A*!2'6%<!*$%!+3((%6*!81*%!168!*'7%!,6!*$%!
)%(0%(5!G_%%4!'6!7'68!*$1*!*$%!81*%!,6!*$%!@(,=)%(!168!)%(0%(!7'9$*!6,*!@%!'6!).6+5H
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
\Z(,83+*)!Z19%]!GC'93(%!"D5"^H5!#$%!01('1@2%!')!1))'96%8!1!)*('69!,&!1(937%6*)!*$1*!='22!
@%!)%6*!*,!*$%!ZWZ!date()!&36+*',6!,6!*$%!6%A*!2'6%<!*$%!+3((%6*!81*%!168!*'7%!,6!*$%!
)%(0%(5!G_%%4!'6!7'68!*$1*!*$%!81*%!,6!*$%!@(,=)%(!168!)%(0%(!7'9$*!6,*!@%!'6!).6+5H
>
#$%!+,,-'%!')!)%*!='*$!*$%!setcookie()!&36+*',65!#$%!&'()*!1(937%6*<!"message"<!')!*$%!
617%!,&!*$%!+,,-'%!168!*$%!)%+,68!1(937%6*<!"$last_visit"<!')!*$%!0123%!*$1*!='22!@%!
)*,(%8!'6!*$%!+,,-'%5
E
#$%!&'()*!*'7%!*$')!419%!')!1++%))%8!*$%!+,,-'%!')!)%*5!F*)!0123%!='22!6,*!@%!101'21@2%!36*'2!
*$%!6%A*!*'7%!*$%!419%!')!0'%=%85!F&!*$%!+,,-'%!$1)!1!0123%!G'5%5<!')!6,*!%74*.H<!*$%!
7%))19%!='22!+,6*1'6!*$%!81*%!)*('69!*$1*!=1)!1))'96%8!*,!*$%!+,,-'%!@.!*$%!setcookie()!
&36+*',6!'6!*$%!4(%0',3)!0'%='69!,&!*$%!419%5
O
#$%!0123%!,&!*$%!+,,-'%!')!%A*(1+*%85!F*!')!*$%!81*%!)*('69!*$1*!=1)!1))'96%8!*,!*$%!+,,-'%!
*$%!21)*!*'7%!*$%!0')'*,(!0'%=%8!*$')!419%5!`0%(.!*'7%!*$%!0')'*,(!(%&(%)$%)!*$')!419%<!*$%!

0123%!,&!*$%!+,,-'%!='22!@%!*$%!+,,-'%!0123%!*$1*!=1)!)%*!,6!$')!,(!$%(!21)*!0')'*<!*$1*!')<!
*$%!81*%!168!*'7%!,&!*$%!21)*!0')'*5
!
Figure 16.9. The HTML initial form (page 1).
!
!








Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Figure 16.10. After returning to this page, the cookie value is displayed.
!

16.3.3. Extending the Life of a Cookie
How long will a cookie stay in the cookie jar? Normally a cookie expires when the browser is exited. However, the
cookie’s life span can be controlled by setting the expiration date in the cookie’s expire attribute, the third argument
in PHP’s setcookie() function. The time the cookie expires is represented as a UNIX timestamp; that is, the
number of seconds since January 1, 1970, 00:00:00 GMT, known as the epoch. The time() function will give you the
current time in seconds, and by adding additional seconds, you can set the expiration date of a cookie to some time in
the future. By subtracting from this value, the time will be past time, which will cause the cookie to be deleted. The
time returned is expressed in GMT time, the required format for the expire attribute.
To get the time, two PHP functions are provided: time() and mktime().
The time() Function
The time() function returns the current time in UNIX time (UNIX timestamp). By adding the number of seconds to
the output of the time() function, you can set the amount of time from now until some future time when the cookie is

to expire.
Table 16.1. Units of Time in Seconds
Unit%of%Time
Seconds
X'63*%
60
W,3(
60 * 60
a1.
60 * 60 * 24
S%%-
60 * 60 * 24 * 7
X,6*$
60 * 60 * 24 * 30
!




Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Format
int time ( void )
!
Example:
$nextWeek = time() + (60 * 60 * 24 * 7); (60 seconds * 60 minutes *
24 hours * 7 days)

Example 16.5.
<?php
$date_str="l dS \of F Y h:i:s A";

$last_visit="Your last visit was on ". date("$date_str");
1 $expire=60*60*24*30 + time(); // One month
2 setcookie("message","$last_visit", $expire);
?>
Explanation
"
#$%!01('1@2%!')!1))'96%8!*$%!0123%!,&!,6%!7,6*$<!>^!81.)<!&(,7!6,=!'6!
7'22')%+,68)5
:
#$%!setcookie()!&36+*',6!')!617%8!message<!'*!+,6*1'6)!*$%!81*%!,&!*$%!21)*!
0')'*<!168!'*!='22!%A4'(%!'6!,6%!7,6*$5!#$%!expire!0123%!')!+12+321*%8!@.!188'69!
*$%!637@%(!,&!)%+,68)!'6!1!7,6*$!*,!*$%!+3((%6*!*'7%!Gtime()H5!I&*%(!,6%!
7,6*$<!'&!*$%!0')'*,(!(%*3(6)<!*$%!+,,-'%!='22!@%!(%)%*5

The mktime() Function
The mktime() function will also get the UNIX time. It has a different format. Arguments can be set to 0 (zero) from
left to right if you want to use the default values. However, you can leave out arguments on the right side to get the
defaults. (The year is either two or four digits.)
Format
int mktime ( [int hour [, int minute [, int second [, int month [,
int day [, int year [, int is_dst]]]]]]] )
!
Example:
$lastday = mktime(0, 0, 0, 6, 0, 2006); // Last day of May echo
date("M-d-Y", mktime(0, 0, 0, 1, 1, 2006)); // "Jan-01-2006"

16.3.4. Buffering and HTTP Headers
Because cookies are sent in an HTTP header, you cannot execute any other output before sending the header or you will
get a PHP warning. In the following example, the fact that there is a blank line at the top of the file caused the warning.
The cookie headers must be set first unless you turn on buffering.

Example 16.6.
< this blank line caused a warning !!!
<?php
setcookie("usr","Ellie Quigley"); // Headers must be sent
first
setcookie("color","blue");
?>
<html>
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
<head><title>The Cookie Array?</title></head>
<body bgcolor="lavender">
< Code continues here >
</body>
</html>
Explanation
The header information must be sent first, or a warning is issued, as in Figure 16.11. Even a blank line will cause a
warning.
Figure 16.11. Header information should be sent first!
!

If you need to precede any HTTP headers (not just cookie headers) with other output, PHP provides a set of buffering
functions that allow you to save all the script’s output in a buffer until the script ends (starting with PHP 4.0). When the
script ends, first the HTTP headers, and then the contents of the output buffer, are sent to the browser.
The functions that help you control output buffering are shown in Table 16.2.




Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Table 16.2. Buffering Functions

Function
What%It%Does
ob_start()
`61@2%)!,3*43*!@3&&%('695!;,!,3*43*!')!)%6*!&(,7!*$%!)+('4*!G,*$%(!*$16!
$%18%()H5!F*!')!)10%8!'6!16!'6*%(612!@3&&%(5
ob_end_flush()
C23)$%)!*$%!,3*43*!@3&&%(<!168!8')1@2 %)! ,3*43*!@3&&%('695
ob_end_clean()
J2%16)!*$%!,3*43*!@3&&%(!='*$,3*!)%6 8'69!'*<!168!8')1@2%)!,3*43*!
@3&&%('695
ob_get_clean()
b%*3(6)!*$%!+,6*%6*)!,&!*$%!,3*43*!@3&&%(!168!%68)!,3*43*!@3&&%('69
ob_get_length()
b%*3(6)!*$%!2%69*$!,&!*$%!,3*43*!@3&&%(5
ob_get_contents()
b%*3(6)!*$%!+3((%6*!,3*43*!@3&&%(!1)!1! )*('695!#$')!122,=)!.,3!*,!4(,+%))!
=$1*%0%(!,3*43*!*$%!)+('4*!%7'**%85
ob_gzhandler()
I!+122@1+-!&36+*',6!&,(!ob_start()5!c)%&32!&,(!)%68'69!+,74(%))%8!81*15
!
The ob_start() and ob_end_flush() Functions
The ob_start() function enables output buffering and the ob_end_flush() function flushes out the buffers and
then turns buffering off. When your script ends, PHP will automatically flush the buffers, so you can omit
ob_end_flush(). It is possible to call ob_start() multiple times; and if so, you would have to call
ob_end_flush() for each level.
Format
bool ob_start ( [callback output_callback [, int chunk_size [,
bool erase]]] ) bool ob_end_flush ( void )
!
Example:

ob_start(); ob_end_flush();

Example 16.7.
J,8%!K'%=L!!
<?php
1 ob_start(); // Turn on output buffering
?>

<html><head><title>The Cookie Array?</title>
</head>
<body bgcolor="lavender">
<font face="verdana" size='+1'>
<h2>$_COOKIE[]</h2>

<?php
2 setcookie("usr","Ellie Quigley");

setcookie("color","blue");
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
?>

<?php
if(! empty($_COOKIE[color])){
echo "<pre>";
print_r($_COOKIE);
echo "</pre>";
}

?>


</font>
</body>
</html>
<?php
3 ob_end_flush(); // Flush the buffer and end output
buffering
?>
Explanation
"
#$%!ob_start()!&36+*',6!*3(6)!,6!,3*43*!@3&&%('695!;,=!,62.!W##Z!$%18%()!
='22!@%!)%6*!168!*$%!(%)*!,&!*$%!4(,9(17V)!,3*43*!='22!@%!)10%8!36*'2!*$%!
4(,9(17!%68)<!1*!=$'+$!*'7%!'*!='22!@%!)%6*5
:
#$%!setcookie()!&36+*',6!+16!@%!421+%8!@%2,=!*$%!,*$%(!,343*!='*$,3*!
+13)'69!=1(6'69)5!#$')!,3*43*!='22!@%!)%6*!&'()*!83%!*,!*$%!@3&&%('69!)%*!34!,6!
2'6%!"5
>
#$%!ob_end_flush()!&36+*',6!')!6,*!6%+%))1(.<!@3*!')!3)%8!$%(%!*,!&23)$!,3*!*$%!
@3&&%()!168!%68!*$%!,3*43*!@3&&%('69!&,(!*$')!)%))',65

Output Buffering and php.ini
If you want buffering set for all your PHP scripts, you can enable the php.ini directive output_buffering. If
you do, every PHP script will behave as if it begins with a call to ob_start().
From the php.ini file:
!
J,8%!K'%=L!
; Output buffering allows you to send header lines (including cookies) even
; after you send body content, at the price of slowing PHP's output layer a
; bit. You can enable output buffering during runtime by calling the output
; buffering functions. You can also enable output buffering for all files by

; setting this directive to On. If you wish to limit the size of the buffer
; to a certain size -you can use a maximum number of bytes instead of 'On', as
; a value for this directive (e.g., output_buffering=4096).
output_buffering = Off

!
Output buffering is turned off by default. If you want to turn it on for all scripts, go to the php.ini initialization file
and change the output_buffering directive to “On”.

Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
16.3.5. Deleting a Cookie
When cookies are created, they are, by default, deleted when the user closes his or her browser. You have seen how to
expand the life of a cookie, but what if you want to delete the cookie right now, even before the user closes his or her
browser? Instead of adding to the current time, you simply subtract from the current time to some earlier date. This will
cause the cookie to be deleted right away.
Remember, deleting a cookie is the responsibility of the browser and the time settings there might be different from the
time settings on the server. Even though technically setting the expiration time to –1 would be an earlier time, it might
be better to set it to a bigger negative number to assure that it will be removed. Setting the expiration time to 0 has no
effect.
Example 16.8.
<?php
setcookie ("cookie_name", "", time( ) - 3600); // One hour
ago
?>
Explanation
Because we are destroying the cookie, there is no point in giving it a value, thus the second argument is
intentionally left empty.
Using the Browser to Remove Cookies
Another way to delete cookies is to go in your browser to the Tools menu in Navigator, then to the Cookie Manger, and
then to Manage Stored Cookies. In Internet Explorer, go to the Tools menu and Internet Options. Then you can remove

all or some cookies from the hard drive. Figure 16.12 shows you how the Firefox browser manages cookies by going to
Tools, Options, Privacy.
Figure 16.12. Cookie management on the Firefox browser.
!
!
16.4. What Is a Session?
Simply put, a session is the time that a user spends at a Web site. PHP provides us with a mechanism to manage
sessions so that we can keep track of what a visitor is doing, what he or she likes, what he or she wants, and so on, even
after the user logs off. Like cookies, the idea is to maintain state. Before delving into the details, let’s use an analogy to
give you an idea of how sessions work.
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Imagine taking your favorite wool sweater to a dry cleaning establishment. You will drop off the sweater and be handed
a claim ticket that will be used to identify the sweater when you return. The other half of the claim ticket is pinned to
your sweater with the same number you have on your claim ticket. Later when you come back, you will give your claim
ticket to the attendant and he or she will use it to identify your sweater in the long rack of clothes. A session works the
same way.
A PHP session, like a cookie, is a way for the PHP to keep track of that Web site visitor even after he or she leaves or
logs off. A visitor makes a request from his or her browser to retrieve a Web page as follows:
http://server/homepage.php
!
The server program, in this example, homepage.php, is a PHP program. PHP starts a session and sends a unique
session ID number, similar to the claim ticket, back to the visitor’s browser. This unique ID number is a long random
hexadecimal number that is used to key into the user’s data. It can be sent via a cookie or added to all URLs of the
pages for the site. The actual user information is saved in a session file on the server, usually in a temporary directory
(see Figure 16.13). The session filename contains the unique ID number for the session. The next time the visitor asks
for the page, his or her browser hands the ID number back to the server, just as you hand the claim ticket to the dry
cleaning attendant. The server uses the session ID number to locate the file with the name that corresponds to the same
session ID number. The session file contains the actual session data; for example, username, preferences, or items in the
shopping cart—information about the visitor that was stored the last time he or she visited the page. If this is the first
time the user has visited the page, his or her preferences will be collected and stored into the session file, to be retrieved

later on.
Figure 16.13. The session data is stored in a /tmp directory on the server.
!
!
!
By default, the session ID is sent in a cookie and the cookie’s name is PHPSESSID. Unlike the cookies we discussed in
the first part of this chapter, where the user information was passed in a cookie, with sessions, the only data in the
cookie is the session ID, not any other information about the user. The user information is saved in a session file on the
server so that the size limitation of cookies is not a factor and sensitive information is not being passed back and forth
across the network.
This session file starts with “sess” followed by the session number (Apache/Windows). The text it contains is a
serialized line representing the data, the data type, and the number of characters saved for a session.
[2]
This is a line
from a session file:
[2]
Because the (session) library uses different storage modules, you can keep the
data in plain-text files, shared memory, or databases. The exact location of data is
not really important (as long the performance of the medium is sufficient). From
Tobias Ratschiller,
book|s:7:"History";user|s:13:"Ellie Quigley";
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
!
Once the user’s browser has a session ID, it passes that ID back to the server program on every subsequent request. The
session ID is disposable, so after some time it will expire and the information associated with it will also be removed. A
session might last for a few minutes or a few hours since the last request or it could last indefinitely. We look at various
configuration options later in this chapter. Figure 16.14 illustrates the way the session ID is passed in a cookie.
Figure 16.14. The cookie file and the session file have the session ID in common.
!
!

!
Although cookies are the default way to pass the session ID back and forth between browser and server, you can also
pass the session ID as GET or POST data in the same way as when submitting a form. Recall that GET data is URL-
encoded and attached with a ? to the URL, whereas the POST data is part of the page header information. It is also
possible to send a session ID through a URL with a link within a page.
16.4.1. Where to Store Sessions
If your site is sharing a server, it is recommended that session files for users should be in their own user area under the
server, but not in a world writable directory such as /tmp. If a site has a large number of users and session files, it is
possible to store the session files in multiple levels of subdirectories. To find out where your sessions are stored, or to
change the default path, see session.save_path in the php.ini file or use PHP’s session_save_path()
function.
From the php.ini file:
; session.save_path = "N;/path" ; ; where N is an integer. Instead of storing
all the session files in ; /path, what this will do is use subdirectories N-
levels deep, and ; store the session data in those directories. This is useful
if you ; or your OS have problems with lots of files in one directory, and is ;
a more efficient layout for servers that handle lots of sessions. ;
!
The session_save_path() function returns the path of the current directory used to save session data. If a path is
specified, the path to where data is saved will be changed for this session. If this page will be linked to other pages, then
the function must be called before starting the session in all the pages involved. Of course, PHP will need read and
write access to the new path to retrieve and save session data.
Format
string session_save_path ( [string path] )
!
Example:
session_save_path("/newpath"); echo session_save_path();
!
Example 16.9.
<?php

echo "Your session files are stored in <b>".
1 session_save_path(). ".</b>< br />";
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
2 if ($handle = opendir(session_save_path())) {
echo "<b>Files:< br />\n";
/* Loop over the directory. */
3 while (false !== ($file = readdir($handle))) {
echo "$file< br />\n";
}
echo "</b>";
closedir($handle);
}
?>
Explanation
"!
#$%!session_save_path()!&36+*',6!(%*3(6)!*$%!41*$!2,+1*',6!=$%(%!*$%!)%))',6!&'2%)!1(%!
)*,(%85!
:!
#$%!opendir()!&36+*',6!,4%6)!*$%!8'(%+*,(.!&,28%(!=$%(%!*$%!)%))',6!81*1!')!)*,(%8!168!
(%*3(6)!1!$1682%!*,!*$1*!8'(%+*,(.<!$handle5!
>!
#$%!(%188'(GH!&36+*',6!(%*('%0%)!*$%!+,6*%6*)!,&!*$%!8'(%+*,(.<!168!'*)!,3*43*!')!8')421.%8!
'6!C'93(%!"D5"O5!
!
Figure 16.15. The session path and files. Output from Example 16.9.
!
!
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
16.4.2. Starting a Cookie-Based Session
A PHP session is started either explicitly with the session_start() function, or implicitly by registering a variable

for the session with the session_register() function. Typically, session_start() is called on top of the
page, and then session variables are registered in the superglobal $_SESSION array.
When PHP starts a session, it has to check first to see whether a valid session ID already exists for this user. If a valid
session ID does exist, PHP will go to the session file that corresponds to the ID number, retrieve the data from the file,
and assign it to the superglobal $_SESSION associative array. The values in this array are then made available to your
program. If this is the first time the user has visited the page, PHP will create a new session ID, and the $_SESSION
array will be empty.
The session_start() Function
The session_start() function creates a session or resumes one that has already started. The session ID is passed
via a cookie, via GET/POST, or in a link (see a cookie-based session in Figure 16.16). Each page that uses a session
must start the session with the session_start() function. If the session ID is being sent by a cookie, then as with
all cookie headers, the session_start() function is called before any other statements that send output to the
browser. This function always returns TRUE.
Figure 16.16. A cookie-based session. Note the session ID is sent as an HTTP Cookie header.
!
!
!
Format
bool session_start ( void )
!
Example:
session_start();
!
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
16.4.3. Registering a Session
The data that is stored in the session file is created in a PHP script in the form of variables. The session variables can
then be referenced across page requests during the life of a session. These variables might represent the items placed in
a shopping cart, a user’s login and password, a user’s color preference, and so on.
Although session_start() starts a session, it does not register session variables. To create session variables, you
must register the variables in the session library. This can be done in two ways. We address both methods next.

The $_SESSION Associative Array
To register variables for the session, the preferred way is to assign values to the superglobal $_SESSION array.
Superglobals are available everywhere in your script, even within functions. PHP automatically registers the
$_SESSION variables for you. The global $_SESSION associative array is used to handle the session variables that
will be saved on the server for the life of the session. The key for the $_SESSION associative array is the name of the
variable, and the value is what you are assigning to it.
To access the values in the $_SESSION associative array, you must first start a session and then extract the array
values as you would any other associative array.
To unset these variables, the unset() function is used; for example, unset($_SESSION['color']).
You must use session_start() before using the $_SESSION array.
Format
!
Example:
$_SESSION['username'] = "john"; $_SESSION['password'] = $_POST['passwd'];
!
Example 16.10.
<?php
1 session_start();
?>
<html><head><title>Sessions</title></head>
<body bgcolor="lavender">
<font size=+1 face="arial">
<h2>Tracking Visitors with Sessions</h2>
<?php
2 if ( ! isset($_SESSION)){
3 $_SESSION[visitor_count]=0;
}
else{
4 $_SESSION[visitor_count]++;
}

5 echo "You are visitor number
",$_SESSION['visitor_count'],".
<br />";
6 echo "The session id is: ",session_id();
?>
</font>
</body>
</html>
Explanation
"!
#$%!)%))',6!')!)*1(*%8!$%(%5!I22!)+('4*)!3)'69!)%))',6)!)*1(*!='*$!*$%!session_start()!
&36+*',65!
:!
F&!*$%!)%))',6!01('1@2%!$1)!6,*!@%%6!)%*<!*$')!')!*$%!)*1(*!,&!1!@(168!6%=!)%))',65!I!)%))',6!
Fa!='22!@%!1))'96%8!168!*$%!$_SESSION!1((1.!='22!@%!'6'*'12'M%8!,6!*$%!6%A*!2'6%5!
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Fa!='22!@%!1))'96%8!168!*$%!$_SESSION!1((1.!='22!@%!'6'*'12'M%8!,6!*$%!6%A*!2'6%5!
>!
#$%!-%.!'6!*$%!$_SESSION!1)),+'1*'0%!1((1.!')!visitor_count5!#$%!0123%!1))'96%8!*,!'*!')!
05!
E!
d6+%!*$%!3)%(!(%&(%)$%)!*$')!419%<!*$%!0123%!,&!*$%!$_SESSION!')!'6+(%7%6*%8!@.!"!G)%%!
C'93(%!"D5"PH5!
O!
`0%(.!*'7%!*$%!0')'*,(!(%*3(6)!*,!*$')!419%<!*$%!+,36*!')!'6+(%7%6*%8!@.!"!168!*$')!2'6%!
8')421.)!*$%!,3*43*<!1)!)$,=6!'6!C'93(%!"D5"R5!
D!
#$%!session_id()!&36+*',6!(%*3(6)!*$%!0123%!,&!*$%!+3((%6*!)%))',6!Fa5!
!
Figure 16.17. Using the $_SESSION array to save and retrieve a session. Initial output from Example 16.10.

!
!
!
Figure 16.18. Each time the user refreshes this page, the count is incremented by 1.
!
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
!
!
The session_register() Function
The traditional way to register session variables was to use the PHP session_register() function, but to use this
function you must set register_globals to “On” in the php.ini file, no longer the default setting. If, on the
other hand, you are using the session_register() function, once registered in the session library, these global
variables will be available until the session ends or until the session_unregister() function is called. Unlike
registering session variables with the $_SESSION array, with the session_register() function it is not
necessary to call session_start() first. After registering a variable, PHP will make an implicit call to
session_start().
The arguments to session_register() can be strings containing the name of a variable or an array name. Note
that this function takes the name of a variable as argument, not the variable itself.
The session_is_registered() function can be used to check if a session variable has been set and
session_unregister() to remove variables from the session; for example, to remove a product item from the
shopping cart. These functions should not be used if you are registering sessions with the $_SESSION array.
Format
bool session_register ( mixed name [, mixed ] )
!
Example:
session_start(); session_register('username'); session_register('password');
!
16.4.4. Saving Arrays in a Session
When using a shopping cart, you can add multiple items to your cart, browse around, come back, delete some items,
and go on like this until you submit your order. A program that collects this data can store it in an array and save the

data with a session. The $_SESSION array accepts simple scalar variables, but can also accept arrays. The following
example demonstrates how to register multiple items in a session, list the saved values on another page, return to the
selection page, and add more items to the array.
Example 16.11.
J,8%!K'%=L!
(Page 1)
<?php

Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
1 session_start();
2 if ( ! isset($_SESSION['choices'])){
3 $_SESSION['choices']=array();
}
4 if ( is_array( $_POST['books'])){
5 $items=array_merge($_SESSION['choices'],
$_POST['books']);
6 $_SESSION['choices'] =array_unique($items);
7 header("Location: listing_page.php"); // Redirect to
this
// page now!
}
?>

<html>
<head><title>Arrays and Sessions</title></head>
<body bgcolor="#6666ff">
<font face="verdana" >
<div align="center">
8 <form action="<?php echo $_SERVER['PHP_SELF']?>" method="POST">
<p>

Book Categories< br />
9 <select name="books[]" multiple=multiple size="8">
<option>Art</option>
<option>Computer</option>
<option>Engineering</option>
<option>Fiction</option>
<option>Language</option>
<option>Non Fiction</option>
<option>Poetry</option>
<option>Travel</option>
</select>
</p>
<input type=submit value="Select category"/>
</p>
</font>
</body>
</html>

Explanation
"!
I!)%))',6!&,(!*$')!419%!')!)*1(*%85!I22!)+('4*)!*$1*!3)%!)%))',6)!73)*!+122!*$%!
session_start()!&36+*',65!
:<!
>!
F&!*$')!')!*$%!&'()*!*'7%!*$%!0')'*,(!$1)!0'%=%8!*$')!419%<!*$%!)%))',6!01('1@2%)!
='22!6,*!@%!)%*5!F6!2'6%!>!*$%!array()!&36+*',6!71-%)!)3(%!*$%!
$_SESSION['choices']!1((1.!')!+(%1*%8!='*$!6,!0123%)5!
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
E!
F&!*$%!&,(7!$1)!@%%6!)3@7'**%8<!$_POST['books']!='22!+,6*1'6!1!2')*!,&!*$%!

@,,-)!)%2%+*%8!&(,7!*$%!7%63!'6!*$%!&,(75!
O!
#$%!array_merge()!&36+*',6!T,'6)!*$%!0123%)!'6!$_SESSION['choices']!168!
*$%!@,,-)!*$1*!=%(%!2')*%8!'6!*$%!&,(7<!$_POST['books']5!F&!*$')!')!*$%!&'()*!
*'7%!*$%!3)%(!$1)!0')'*%8!*$%!419%<!*$%!$_SESSION[]!1((1.!='22!@%!%74*.<!@3*!'*!
='22!%A')*!@%+13)%!'*!=1)!)%*!*,!*$%!%74*.!1((1.!,6!2'6%!>5!
D!
F&!*$')!')!6,*!*$%!&'()*!0')'*!168!*$%!$_SESSION['choices']!1((1.!$1)!0123%)!
&(,7!1!4(%0',3)!)%))',6<!*$%!array_unique()!&36+*',6!='22!(%7,0%!16.!
8342'+1*%)!*$1*!7'9$*!,++3(!1&*%(!*$%!7%(9%!,6!2'6%!O5!
P!
#$%!0')'*,(!')!(%8'(%+*%8!*,!419%!:<!listing_page.php<!*,!)%%!$')!,(!$%(!
+3((%6*2.!)10%8!)%2%+*',6!,&!@,,-)5!
R!
#$')!')!1!)%2&N4(,+%))'69!&,(75!d6+%!*$%!0')'*,(!$1)!&'22%8!,3*!*$%!&,(7<!*$%!ZWZ!
+,8%!,6!*$')!419%!='22!4(,+%))!'*!168!*$%6!(%8'(%+*!*$%!3)%(!*,!419%!:5!
[!
#$%!W#XY!)%2%+*',6!2')*!')!617%8!"books[]"!G)$,=6!'6!C'93(%!"D5"[H<!*$%!
617%!,&!*$%!1((1.!ZWZ!='22!3)%!*,!+,22%+*!*$%!0')'*,(V)!@,,-!+$,'+%)5!
Figure 16.19. Page 1: The visitor selects some books.

!
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Example 16.12.
J,8%!K'%=L!
(Page 2)
<?php
1 session_start();
?>


<html><head><title>Listing User's Book
Categories</title></head>
<body bgcolor="#6666FF">
<font face="verdana">
<table width="25%" border='1'>
<caption><b>Selected Book Categories</b></caption>
<col span="1" width="100"/>
<?php
2 if ( is_array($_SESSION['choices'])){
3 foreach($_SESSION['choices'] as $book){
?>
4 <tr bgcolor="#ffffff"><td ><?php echo $book ?></td></tr>
<?php
} // End foreach block
} // End if block
else{ echo "<p>You have not selected any book categories
yet</p>";}
?>
</table>
<p>
5 <a href="selections_page.php">Click here to return to category
page</a>
</p>
</font>
</body>
</html>
Explanation
"
I!)%))',6!')!)*1(*%8!&,(!*$')!419%5
:

F&!$_SESSION['choices']!$1)!0123%)<!*$%6!*$%!3)%(!$1)!)%2%+*%8!@,,-)!'6!1!4(%0',3)!
)%))',6<!168!*$%!)*1*%7%6*)!'6!*$%!if!@2,+-!='22!@%!%A%+3*%85
>
#$%!foreach!2,,4!')!3)%8!*,!'*%(1*%!,0%(!*$%!1((1.!168!2')*!%1+$!,&!*$%!@,,-)!'6!*$%!
$_SESSION['choices']!1)),+'1*'0%!1((1.5
E
#$%!@,,-)!)%2%+*%8!@.!*$%!3)%(!1(%!8')421.%8!'6!*$%!*1@2%!)$,=6!'6!C'93(%!"D5:^5
O
#$')!2'6-!')!3)%8!*,!)%68!*$%!3)%(!@1+-!*,!*$%!&'()*!419%<!)$,=6!'6!C'93(%!"D5:"5!I&*%(!
)%2%+*'69!16,*$%(!@,,-!'*%7!&(,7!*$%!?,,-!J1*%9,('%)!'6!*$%!,('9'612!&,(7<!*$%!6%=!
)%2%+*',6!')!)10%8!@.!*$%!)%))',6!168!(%8')421.%8!'6!C'93(%!"D5::5
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.

×