Vous êtes sur la page 1sur 6

PHP Cookies

Cookie s are text file s st ored o n the client c o m p uter and the y are k ept of u s e
tracking p urpo s e. PHP tran s parentl y s u p p orts HTTP c o o kie s.
There are three st ep s in v ol v e d in id entif ying returning u s er s:
• Serv er s cript s e n d s a s et of c o okie s to the bro w s er. For e xa mple na m e,
ag e, or identification nu mb er etc.
• Bro w s er store s this information o n local machine for future u s e.
• When n e xt time bro w s er s e n d s an y requ e st to w e b s er v er then it s e n d s
th o s e c o o kie s information to the s er v er and s er v er u s e s that information
to identif y th e u s er.
Thi s chapter will teach y o u h o w to s et c o o kie s, h o w to acc e s s the m and h o w to
d elete the m.

The Anatomy of a Cookie:
Cookie s are u s uall y s et in an HTTP h ead er (although JavaScript can als o s et a
c o o kie directl y o n a bro w s er). A PHP s cript that s et s a c o o kie might s e n d
h ead ers that look s o m ething like this:
HTTP/1.1 200 OK
Date: Fri, 04 Feb 2000 21:03:38 GMT
Server: Apache/1.3.9 (UNIX) PHP/4.0b3
Set­Cookie: name=xyz; expires=Friday, 04­Feb­07 
22:03:38 GMT; 
                 path=/; domain=tutorialspoint.com
Connection: close
Content­Type: text/html

A s y o u can s e e, the Set - Cookie h ead er c ontain s a na m e valu e pair, a GMT date,
a path and a d o main. The na m e and v alu e w ill b e URL e nc od e d. The e x pire s
field is an in struction to the bro w s er to "forget" th e c o okie after th e gi v e n tim e
and date.
If the bro w s er is c onfigured to st ore c o o kie s, it w ill th en k e ep this information
u ntil the e x piry date. If the u s er p oints the bro w s er at an y page that match e s
th e path and d o main of th e c o o kie, it w ill re s e n d the c o okie to the s er v er.The
bro w s er's h ead er s might look s o m ething like this:
GET / HTTP/1.0
Connection: Keep­Alive
User­Agent: Mozilla/4.6 (X11; I; Linux 
2.2.6­15apmac ppc)
Host: zink.demon.co.uk:1126
Accept: image/gif, */*
Accept­Encoding: gzip
Accept­Language: en
Accept­Charset: iso­8859­1,*,utf­8
Cookie: name=xyz
A PHP s cript w ill the n ha v e acce s s to the c o o kie in the e n viron m e ntal v ariable s
$_COOKIE or $HTTP_COOKIE_VARS[] w hich h old s all c o okie na m e s and valu e s.
Ab o v e c o o kie can b e acce s s e d u sing $HTTP_COOKIE_VARS["name"].

Setting Cookies with PHP:
PHP pro vid ed s etc o o kie() function to s et a co okie. This fun ction require s upto
six argu m ent s and s h o uld b e called b efore < h t ml > tag. For each c o o kie thi s
function ha s to b e called s e paratel y.
setcookie(name, value, expire, path, domain, 
security);

Here is the d etail of all the argu m e nt s:


• Nam e - This s et s the na m e of the c o o kie and is st ored in an e n viron m e nt
v ariable called HTTP_COOKIE_VARS. This variable is u s e d w hile
acc e s sing c o okie s.
• Value - This s et s th e v alu e of the nam e d variable and is the c ontent that
y o u actually w ant to st ore.
• Expiry - This s p e cif y a future tim e in s e c o n d s sin ce 0 0:00:00 GMT o n 1 st
Jan 1 9 7 0. After this time c o okie will b ec o m e inacc e s sible. If thi s
parameter is n ot s et then c o okie w ill auto matically e x pire w h e n the Web
Bro w s er is clo s e d.
• Path - This s p e cifie s the directorie s for w hich the c o o ki e is valid. A single
for ward sla s h character p ermits the c o okie to be v alid for all directorie s.
• Do main - This can b e u s e d to s p e cif y the d o main nam e in v er y large
d o main s and m u st c ontain at least t w o p eriod s to b e valid. All c o o kie s
are o nl y v alid for th e h o st and d o main w hich created th e m.
• Security - This can b e s et to 1 to s p ecif y that the c o okie s h o uld o nl y be
s e nt b y s e c ure tran s mi s si on u sing HTTPS oth er wi s e s et to 0 w hich m ean
c o o kie can be s e nt b y regular HTTP.
Follo wing e xa mple w ill create t w o c o o ki e s nam e and age the s e c o okie s will be
e x pired after o n e h our.
<?php
   setcookie("name", "John Watkin", time()+3600, 
"/","", 0);
   setcookie("age", "36", time()+3600, "/", "",  0);
?>
<html>
<head>
<title>Setting Cookies with PHP</title>
</head>
<body>
<?php echo "Set Cookies"?>
</body>
</html>
Accessing Cookies with PHP
PHP pro vid e s man y w a y s to acc e s s c o o kie s.Simple st w a y is to u s e eith er
$_COOKIE or $HTTP_COOKIE_VARS v ariable s. Follo wing e xa mple w ill acce s s
all the c o o kie s s et in abo v e e xa m ple.
<html>
<head>
<title>Accessing Cookies with 
PHP</title>
</head>
<body>
<?php
echo $_COOKIE["name"]. "<br />";
/* is eq uivalent to */
echo $HTTP_COOKIE_VARS["name"]. 
"<br />";

echo $_COOKIE["age"] . "<br />";
/* is eq uivalent to */
echo $HTTP_COOKIE_VARS["name"] . "<br 
/>";
?>
</body>
</html>

You can u s e is s et() function to ch ec k if a co okie is s et or n ot.


<html>
<head>
<title>Accessing Cookies with PHP</title>
</head>
<body>
<?php
  if( isset($_COOKIE["name"]))
    echo "Welcome " . $_COOKIE["name"] . 
"<br />";
  else
    echo "Sorry... Not recognized" . 
"<br />";
?>
</body>
</html>

Deleting Cookie with PHP
Officiall y, to d elete a c o okie y o u s h o uld call s etc o okie() w ith the nam e
argu m e nt o nl y but this d o e s n ot al wa y s w ork w ell, h o w e v er, and s h ould n ot b e
relied o n.
It is saf e st to s et the c o o kie w ith a date that ha s alread y e x pired:
<?php
  setcookie( "name", "", time()­ 60, 
"/","", 0);
  setcookie( "age", "", time()­ 60, 
"/","", 0);
?>
<html>
<head>
<title>Deleting Cookies with PHP</title>
</head>
<body>
<?php echo "Deleted Cookies" ?>
</body>
</html>

PHP Sessions
An alternati v e w a y to mak e data acce s sible acro s s the v ariou s page s of an
e ntire w e b site is to u s e a PHP Ses si on.
A s e s si o n create s a file in a te mp orary director y o n the s er v er w h ere
regist ered s e s si on variable s and their v alu e s are s tored. This data will b e
a vailable to all pag e s on the site d uring that vi sit.
The location of the te m p orary file is d etermin ed b y a s etting in th e p hp.ini file
called s e s si on.sa v e_path. Bore u sing an y s e s si on variable mak e s ure y o u ha v e
s etu p this path.
When a s e s sion is started follo wing thing s happ en:
• PHP first create s a unique id entifier for that particular s e s si on w hich is a
rand o m string of 3 2 h e xad eci mal nu mb ers s u c h as
3 c 7 f oj3 4 c 3jj97 3 hjk op 2fc 9 3 7 e 3 4 4 3.
• A c o o kie called PHPSESSID is auto maticall y s e nt to the u s er's c o m p uter
to st ore unique s e s si on id entification string.
• A file is auto matically created on the s er v er in th e d e signated te mp orary
direct or y and bears the na m e of the uniqu e id entifier prefixe d b y s e s s_ ie
s e s s_3c 7foj3 4 c 3jj9 7 3 hjk op 2fc 9 3 7 e 3 4 4 3.
When a PHP s cript w a nts to retrie v e the v alue fro m a s e s sion variable, PHP
auto matically g et s th e u niqu e s e s si on identifier string fro m the PHPSESSID
c o o kie and then look s in its te mp orary director y for the file b earing that na m e
and a v alidation can b e d on e b y c o m paring both v alu e s.
A s e s si o n e n d s w h e n the u s er lo s e s the bro w s er or after lea vin g the site, the
s er v er w ill terminate th e s e s sion after a pred etermin ed p eriod of time,
c o m m o nl y 3 0 minute s duration.

Starting a PHP Session:
A PHP s e s si on is ea sil y started b y making a call to the s e s si on_start()
function.This fu nction first ch ec k s if a s e s sion is alread y s tarted and if n o n e is
started then it starts o n e. It is reco m m e n d e d to put the call to s e s si on_start() at
th e b eginning of the page.
Ses sio n v ariable s are stored in as s o ciati v e array called $_SESSION[]. The s e
v ariable s can b e acc e s s e d during lifetim e of a s e s si on.
The f ollo wing e xa m ple starts a s e s si on th en regi ster a variable called c ou nter
that is incre m e nted each time the page is vi sited during th e s e s si on.
Make u s e o f is s et() fun ction to ch e ck if s e s si on v ariable is alread y s et or n ot.
Put this c o d e in a te st.php file and load this file man y tim e s to s e e the res ult:
<?php
   session_start();
   if( isset( $_SESSION['counter'] ) )
   {
      $_SESSION['counter'] += 1;
   }
   else
   {
      $_SESSION['counter'] = 1;
   }
   $msg = "You have visited this page ". 
$_SESSION['counter'];
   $msg .= "in this session.";
?>
<html>
<head>
<title>Setting up a PHP session</title>
</head>
<body>
<?php  echo ( $msg ); ?>
</body>
</html>

Destroying a PHP Session:
A PHP s e s si on can b e d e stro y e d b y s e s si on_de stro y() function. This function
d o e s n ot n e e d an y argu m ent and a sin gle call can d e stro y all the s e s si on
v ariable s. If y o u w a nt to d e stro y a single s e s si on variable the n y o u can u s e
u n s et() fun ction to u n s et a s e s si o n variable.
Here is the e xa mple to un s et a single v ariable:
<?php
   unset($_SESSION['counter'
]);
?>

Here is the call w hich w ill d e stro y all the s e s sion v ariable s:
<?php
   session_destroy(
);
?>
Turning on Auto Session:
You d o n't n e ed to call start_s e s si on() function to start a s e s si on w h e n a u s er
v i sit s y o ur site if y o u can s et s e s sion.auto_start v ariable to 1 in php.ini file.

Sessions without cookies:
There ma y be a cas e w h e n a u s er d o e s n ot allo w to st ore c o okie s on their
ma chin e. So there is anoth er m eth od to s e n d s e s si on ID to the bro w s er.
Alternati v el y, y o u can u s e the c o n stant SID w hich is d efin ed if the s e s si on
started. If th e client did n ot s e n d an appropriate s e s si on c o o ki e, it has the form
s e s si o n_na m e = s e s sion_id. Other wi s e, it e xpand s to an e m pt y string. Thu s, y o u
can e m b e d it u nc on ditionall y into URLs.
The f ollo wing e xa m ple d e m o n strate s h o w to register a v ariable, and h o w to
link c orrectl y to an oth er pag e u sing SID.
<?php
   session_start();

   if (isset($_SESSION['counter'])) {
      $_SESSION['counter'] = 1;
   } else {
      $_SESSION['counter']++;
   }
?>
   $msg = "You have visited this page ". 
$_SESSION['counter'];
   $msg .= "in this session.";
   echo ( $msg );
<p>
To continue  click following link <br />
<a  href="nextpage.php?<?php echo 
htmlspecialchars(SID); >">
</p>

The ht ml sp e cialchars() ma y b e u s e d w h e n printing the SID in ord er to pre v e nt


XSS related attack s.

Vous aimerez peut-être aussi