}
?>
</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.
<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+*%(!
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
:<!
>
<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]";
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
$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.
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:
</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
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
!
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
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.
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.
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>
@,,-)!)%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();
?>
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.