08 PHP Sessions and Session Variables Student Version
08 PHP Sessions and Session Variables Student Version
1
PHPCOOKIES,SESSIONS,
AND SESSION VARIABLES
Fall2009 CSCI2910ServerSideWebProgramming
Objectives
UnderstandanduseCookiesinPHPscripts.
UnderstandanduseSessionsandSessionvariables
i i inPHPscripts.
10/18/2009
2
HTTP
HTTPisastatelessprotocol
Eachpage"standsalone"andhasnomemoryofpast
ti actions.
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" "27"); setcookie( cook , 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
3
Deletingandcheckingcookies
Todelete:overwritecookiewithexpirationtimein
thepast.
t ki (" k" "" ti () 100) setcookie("cook","",time()-100);
Actualcookiedeletiondonebyuser'sbrowser.
Toseeiftheuseracceptscookies,writeoneand
then check (on another page or after a refresh) to
http://einstein.etsu.edu/~pittares/CSCI2910/examples/83.php
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
4
Whatissessioncontrol?
Givesabilitytotrackauserthroughsite,andeasily
movedatarelatedtothatuseramongpages.
N d d h h hidd f fi ld Noneedtomovedatathroughhiddenformfields.
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
Session ID corresponds a session data store on SessionIDcorrespondsasessiondatastoreon
server
Asessionwilleventuallyexpireusuallyaftera
specifiedperiodofinactivity.
10/18/2009
5
Progressionofevents
PHPscriptstartsasession.Donebeforeanyother
pageactivity.
i t t() session_start();
SessionIDcreatedandstoredonuser's computer.(if
possible)
Sessionvariablesarecreated,andvaluesstoredon
theserver.
PHPscriptcanusethesevariablesfrompageto
pagethroughoutasite.
Usingsessionvariables
SomePHPserversautomaticallystartaSessionfor
everyuserwhentheyvisitthesite.
M l hi d d h d Mayslowthingsdownduetounnecessaryoverhead.
ControlledbyPHP.ini fileontheserver.
http://einstein.etsu.edu/~pittares/PHPTest/phpinformation.php
SessionoperationschangedinPHP4.1,sobe
carefulwitholderinstallationsandreference careful with older installations and reference
books.
10/18/2009
6
Startingasession
Inanyscript usingsessions,youmustfirstcall
session_start().
If i h b bli h d hi ill d h Ifsessionhasnotbeenestablished,thiswilldothat.
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'] = "Nicks 484";
$_SESSION['phone'] = 96951;
?>
<?php
session start();
http://einstein.etsu.edu/~pittares/CSCI2910/examples/85.php
session_start();
echo "Here's the session info:<br />";
foreach ($_SESSION as $var=>$contents)
echo "$var: $contents<br />";
?>
10/18/2009
7
ManipulatingSessionID
session_id() allowsyoutogetorsetthe
SessionID.
If h S i ID Ifnoparameter,returnstheSessionID.
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 // d / / / l / h
unset() canbeusedtoeraseasinglevariableand
data.
unset($_SESSION['myvar']);
session destroy() destroys the session data
http://einstein.etsu.edu/~pittares/CSCI2910/examples/89.php
session_destroy() destroysthesessiondata
(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
8
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
9
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 d f t i l t h th datamovedfrompagetopageislostwhenthe
userbookmarksapageandreturnslater.
Security
IfausercancounterfeitaSESSIONcookie,theycould
"hijack"anotheruser'sinteractionsession.
10/18/2009
10
SessionIDNumbers
IftheuserallowsCookies,thiswillbehandled
automatically.
f h d ll C ki h IftheuserdoesnotallowCookies,thenasyou
movefrompagetopageyou(theprogrammer)
mustmanuallykeepupwiththeSessionID.
AppendtheSIDtotheURL.
<a href="session2.php?PHPSESSID=<?=SID?>">test</a>
OrturnontransparentSIDsupportinthePHP
configuration
a e sess o .p p? S SS ? S ? test /a
Iftheuseracceptscookies:
IfTransparentSIDison
Iftheuserdoesnotacceptcookies: