Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
PHPCOOKIES,SESSIONS,
AND SESSION VARIABLES
Fall2009
CSCI2910ServerSideWebProgramming
Objectives
UnderstandanduseCookiesinPHPscripts.
UnderstandanduseSessionsandSessionvariables
i
inPHPscripts.
i
10/18/2009
HTTP
HTTPisastatelessprotocol
Eachpage"standsalone"andhasnomemoryofpast
actions.
ti
AddressedinNetscape3.0withcookies.
Cookiesallowustowritedatatouser'scomputer
andreadthatdataasusertraversessite.
Cookies can only be written as part of header
Cookiescanonlybewrittenaspartofheader
information,thereforecannotcreateoraddtoa
cookieafterwritingtobrowser.
Usingcookies
Tocreateacookie,usesetcookie()
setcookie(cookiename, value, [expire]);
setcookie("cook"
setcookie(
cook ,"27");
27 );
Expirationexpressedusingtime.Ifnotset,cookie
isvalidforthisusersessiononly.
setcookie("other","1", time()+60*60*24*30);
http://einstein.etsu.edu/~pittares/CSCI2910/examples/81.php
Retrievedsimilarto$_POSTvariables:
$_COOKIE['cookiename']
http://einstein.etsu.edu/~pittares/CSCI2910/examples/82.php
10/18/2009
Deletingandcheckingcookies
Todelete:overwritecookiewithexpirationtimein
thepast.
setcookie("cook","",time()-100);
t
ki ("
k" "" ti () 100)
http://einstein.etsu.edu/~pittares/CSCI2910/examples/83.php
Actualcookiedeletiondonebyuser'sbrowser.
Toseeiftheuseracceptscookies,writeoneand
then check (on another page or after a refresh) to
thencheck(onanotherpageorafterarefresh)to
seeifitexists.
Cookietutorial:
http://einstein.etsu.edu/~pittares/CSCI2910/examples/84.php
Conclusion:UsingCookies
Ifuseracceptscookies,and ifyourememberto
managesettingthempriortononheaderoutput,
then they're fine
thenthey'refine.
IfyouuseSessions:
PHPmanagescomplexity.
Iftheuserdoesn'tsupportcookies,PHPhasan
automated"workaround".
Morecomplexdatastorage(arrays,etc.)easierto
implement.
But,youlosemultivisitpersistence
10/18/2009
Whatissessioncontrol?
Givesabilitytotrackauserthroughsite,andeasily
movedatarelatedtothatuseramongpages.
Noneedtomovedatathroughhiddenformfields.
N
d
d
h
h hidd f
fi ld
Veryusefulforauthentication,butcanbeusedany
timepersistentdataneededthroughoutasitevisit.
Howsessionswork
Sessionsareidentifiedbyarandomnumber
(SessionID)generatedbyPHPandstoredonthe
client computer in 1 of 2 ways:
clientcomputerin1of2ways:
Usingacookie,iftheuser'sbrowsersupports.
AppendingthesessionnumbertoURLsasuser
traversessite
www.whatever.com?PHPSESSID=495294532459x
SessionIDcorrespondsasessiondatastoreon
Session
ID corresponds a session data store on
server
Asessionwilleventuallyexpireusuallyaftera
specifiedperiodofinactivity.
10/18/2009
Progressionofevents
PHPscriptstartsasession.Donebeforeanyother
pageactivity.
session_start();
i
t t()
SessionIDcreatedandstoredonuser's computer.(if
possible)
Sessionvariablesarecreated,andvaluesstoredon
theserver.
PHPscriptcanusethesevariablesfrompageto
pagethroughoutasite.
Usingsessionvariables
SomePHPserversautomaticallystartaSessionfor
everyuserwhentheyvisitthesite.
Mayslowthingsdownduetounnecessaryoverhead.
M
l
hi
d
d
h d
ControlledbyPHP.ini fileontheserver.
http://einstein.etsu.edu/~pittares/PHPTest/phpinformation.php
SessionoperationschangedinPHP4.1,sobe
careful with older installations and reference
carefulwitholderinstallationsandreference
books.
10/18/2009
Startingasession
Inanyscript usingsessions,youmustfirstcall
session_start().
Ifsessionhasnotbeenestablished,thiswilldothat.
If
i h
b
bli h d hi ill d h
Ifasessionhasbeenestablished,thiswillload
sessiondata.
Youmust startthesessionattheverybeginningof
thescriptaspartofheadertransmission.
p
p
Addoraccesssessionvariablesbyusingthe
$_SESSION superglobal array.
SessionHandling
<?php
session_start();
$_SESSION['name'] = "Dr. Tony Pittarese";
$ SESSION['office'] = "Nicks 484";
$_SESSION['office']
$_SESSION['phone'] = 96951;
?>
http://einstein.etsu.edu/~pittares/CSCI2910/examples/85.php
<?php
session start();
session_start();
echo "Here's the session info:<br />";
foreach ($_SESSION as $var=>$contents)
echo "$var: $contents<br />";
?>
10/18/2009
ManipulatingSessionID
session_id() allowsyoutogetorsetthe
SessionID.
Ifnoparameter,returnstheSessionID.
If
h S i ID
Ifgivenaparameter,setsthatastheSessionID.
http://einstein.etsu.edu/~pittares/CSCI2910/examples/87.php
http://einstein.etsu.edu/~pittares/CSCI2910/examples/88.php
ManipulatingtheSessiondata
session_unset() erasesallsessionvariables
anddata.
h //
http://einstein.etsu.edu/~pittares/CSCI2910/examples/89.php
d /
/
/
l /
h
unset() canbeusedtoeraseasinglevariableand
data.
unset($_SESSION['myvar']);
session_destroy()
session
destroy() destroysthesessiondata
destroys the session data
(withoutdestroyingthesessionvariables).
Canbeusefulfor"loggingout"user.
http://einstein.etsu.edu/~pittares/CSCI2910/examples/810.php
http://einstein.etsu.edu/~pittares/CSCI2910/examples/811.php
10/18/2009
Sessionvariablearrays
Sessionvariablescanbearrays
<?php
session_start();
();
$_SESSION['list'][]="Hello";
$_SESSION['list'][]="Wow";
echo count($_SESSION['list'])."<br />";
foreach ($_SESSION['list'] as $item)
echo "$item<br />";
?>
Canbeusefultechniqueforshoppingcartsorother
datathatisaccumulatedovermultiplepagevisits.
http://einstein.etsu.edu/~pittares/CSCI2910/examples/812.php
WhenandwhytouseSessions
Performance
Whenperformingaslowoperation,storingtheresults
foruseonseveralpagesisbetterthanrepeatingthe
p g
p
g
calculationoneach.
Example:storingresultsofSQLquery
Sequence
Whenauserprocesstakesplaceoverasequenceof
screens,storinginformationsavestimeanduserinput.
Personalization
Sessionvariablescanbeusedtostoreusercoloror
layoutpreferencesorfactsaboutbrowsingactivity.
Pagescanthenadapttothatactivity.
http://einstein.etsu.edu/~pittares/CSCI2910/examples/813.php
10/18/2009
PotentialproblemswithSessions
MultipleServers
Sincesessioninformationstoredonserver,harderto
configure when multiple servers fulfill user
configurewhenmultipleserversfulfilluser
requests.
HandledtypicallybyusingaDBtostoresessiondata.
Performance
Additionalworkloadforservertostoreandretrieve
information.
information
GarbageCollection
Sinceusermayabandonsitevisit,mustdetermine
sessiontimeoutvaluesandemploygarbage
collection.
PotentialproblemswithSessions
Bookmarking
UnlikeGETparameterswhichcanbebookmarked,
d t
datamovedfrompagetopageislostwhenthe
df
t
i l t h th
userbookmarksapageandreturnslater.
Security
IfausercancounterfeitaSESSIONcookie,theycould
"hijack"anotheruser'sinteractionsession.
10/18/2009
SessionIDNumbers
IftheuserallowsCookies,thiswillbehandled
automatically.
IftheuserdoesnotallowCookies,thenasyou
f h
d
ll C ki
h
movefrompagetopageyou(theprogrammer)
mustmanuallykeepupwiththeSessionID.
AppendtheSIDtotheURL.
<a
a href="session2.php?PHPSESSID=<?=SID?>">test</a>
e
sess o .p p?
S SS
? S ?
test /a
OrturnontransparentSIDsupportinthePHP
configuration
IfTransparentSIDison
Iftheuseracceptscookies:
Iftheuserdoesnotacceptcookies:
10