Cookies and sessions


Published on

Published in: Education
  • Be the first to comment

  • Be the first to like this

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

Cookies and sessions

  1. 1. Setting Cookies Pengaturcaraan PHPPengaturcaraan PHPCookies are one way that a site can remember or track a user over the courseof a visit. Think of a cookie like a name tag: you tell the server your name and itgives you a sticker to wear. Then it can know who you are by referring back tothat name tag. 1
  2. 2. To effectively program using cookies, you need to be able to accurately testfor their presence. The best way to do so is to have your Web browser askwhat to do when receiving a cookie. In such a case, the browser will promptyou with the cookie information each time PHP attempts to send a cookie.Different versions of different browsers on different platforms all define theircookie handling policies in different places. To learn more about options forpopular Web browsers, click each bullet point.Internet ExplorerUsing Internet Explorer on Windows XP, choose Tools | Internet Options.Then click the Privacy tab, followed by the Advanced button underSettings. Click "Override automatic cookie handling" and then choose"Prompt" for both First and Third-party Cookies.FirefoxUsing Firefox on Windows, choose Tools | Options. Then click Privacyand expand the Cookies section. Finally, select "ask me every time" inthe Keep Cookies drop-down menu. If you are using Firefox on Mac OSX, the steps are the same, but you must start by choosing Firefox |Preferences. Pengaturcaraan PHP Cookies are sent via the setcookie() function: 2
  3. 3. Pengaturcaraan PHPYou can continue to send more cookies to the browser with subsequentuses of the setcookie() function:Pengaturcaraan PHP Integrate Cookie with PHP variable 3
  4. 4. Pengaturcaraan PHPheader() functionBecause cookies rely upon the HTTP header, you can set them inPHP using the header() function.Its very important to remember that the setcookie() and header()functions must be called before any data is sent to the Web browser. Accessing Cookies Pengaturcaraan PHP 4
  5. 5. Pengaturcaraan PHPTo retrieve a value from a cookie, you only need to refer to the$_COOKIE superglobal, using the appropriate cookie name as the key(as you would with any array). For example, to retrieve the value of thecookie established with the linesetcookie (username, Trout);you would use$_COOKIE[username].Pengaturcaraan PHP Check for the presence of a cookie. 5
  6. 6. Pengaturcaraan PHPWelcome the user, using the cookie.Pengaturcaraan PHP 6
  7. 7. Setting Cookie ParametersPengaturcaraan PHPPengaturcaraan PHPAlthough passing just the name and value arguments to thesetcookie() function will suffice, you ought to be aware of the otherarguments available. The function can take up to four moreparameters, each of which will alter the definition of the cookie:ExpirationPathDomainSecure 7
  8. 8. Pengaturcaraan PHPThe expiration argument is used to set a definitive length of time for acookie to exist, specified in seconds since the epoch (the epoch ismidnight on January 1, 1970). If it is not set, the cookie will continue to befunctional until the user closes his or her browser.Normally, the expiration time is determined by adding a particular numberof minutes or hours to the current moment, retrieved using the time()function. The following line will set the expiration time of the cookie to be 1hour (60 seconds times 60 minutes) from the current moment:Pengaturcaraan PHPThe path and domain arguments are used to limit a cookie to a specificfolder within a Web site (the path) or to a specific host. For example, youcould restrict a cookie to exist only while a user is within the admin folder ofa domain (and the admin folders subfolders): 8
  9. 9. Pengaturcaraan PHPPengaturcaraan PHPSetting the pathSetting the path to / will make the cookie visible within an entire domain(Web site).Setting the domainSetting the domain to will make the cookie visible within anentire domain and every subdomain (,,pages., etc.). 9
  10. 10. Pengaturcaraan PHPFinally, the secure value dictates that a cookie should only be sent over asecure HTTPS connection. A 1 indicates that a secure connection mustbe used, and a 0 signifies that a standard connection is fine. Deleting CookiesPengaturcaraan PHP 10
  11. 11. Pengaturcaraan PHPThe final thing to understand about using cookies is how to delete one. Whilea cookie will automatically expire when the users browser is closed or whenthe expiration date/time is met, sometimes youll want to manually delete thecookie instead.For example, in Web sites that have registered users and login capabilities,you will probably want to delete any cookies when the user logs out. Pengaturcaraan PHP To delete the first_name cookie, you would code: 11
  12. 12. Pengaturcaraan PHPAs an added precaution, you can also set an expiration date thats in the past. Pengaturcaraan PHP 12
  13. 13. Pengaturcaraan PHP Setting Session VariablesPengaturcaraan PHP 13
  14. 14. Pengaturcaraan PHPAnother method of making data available tomultiple pages of a Web site is to usesessions. The premise of a session is thatdata is stored on the server, not in the Webbrowser, and a session identifier is used tolocate a particular users record (sessiondata). This session identifier is normallystored in the users Web browser via acookie, but the sensitive data itself — like theusers ID, name, and so on — alwaysremains on the server.Pengaturcaraan PHPSessions in PHP requires a temporary directory on the server wherePHP can store the session data. For Unix and Mac OS X users, thisisnt a problem, as the /tmp directory is available explicitly forpurposes such as this. For Windows users, you also do not need todo anything special as of version 4.3.6 of PHP. But if you arerunning Windows and an earlier version of PHP, you must configurethe server. Heres how:Create a new folder on your server, such as C:temp.Make sure that Everyone (or just the Web server user, if you knowthat value) can read and write to this folder.Edit your php.ini file, setting the value of session.save_path to thisfolder (C:temp).Restart the Web server. 14
  15. 15. The most important rule with respect to sessions is that each page that willuse them must begin by calling the session_start() function. This functiontells PHP to either begin a new session or access an existing one.The first time this function is used, session_start() will attempt to send acookie with a name of PHPSESSID (the session name) and a value ofsomething like a61f8670baa8e90a30c878df89a2074b (32 hexadecimalletters, the session ID). Because of this attempt to send a cookie,session_start() must be called before any data is sent to the Web browser,as is the case when using the setcookie() and header() functions.Once the session has been started, values can be registered to the sessionusing the following: Pengaturcaraan PHP Replace the setcookie() lines with these lines: 15
  16. 16. Pengaturcaraan PHPPrior to version 4.1 of PHP (when the $_SESSION superglobal becameavailable), session variables were set using the special session_register()function. The syntax wassession_start();$name = Jessica;session_register(name);Its very important to notice that the session_register() function takes thename of a variable to register without the initial dollar sign (so name ratherthan $name).Once a session variable is registered, you can refer to is using$HTTP_SESSION_VARS[var].To delete a session variable, you use the session_unregister() function.Pengaturcaraan PHPUsing session auto_startIf you want, you can set session.auto_start in the php.ini file to 1,making it unnecessary to use session_start() on each page.This does put a greater toll on the server and, for that reason,shouldnt be used without some consideration of the circumstances. 16
  17. 17. Accessing Session Variables Pengaturcaraan PHPPengaturcaraan PHPFor other scripts to be able to accessvariables from a session that has beenstarted, each script must first enable sessions,using session_start().This function will give the current scriptaccess to the previously started session (if itcan read the PHPSESSID value stored in thecookie) or create a new session if it cannot (inwhich case, it wont be able to access storedvalues because a new session will have beencreated).To then refer to a session variable, use$_SESSION[var], as you would refer to anyother array. Lets try this with a script. 17
  18. 18. Pengaturcaraan PHP Add a call to the session_start() function.Pengaturcaraan PHPStep 3Replace the references to $_COOKIE with $_SESSION. 18
  19. 19. Pengaturcaraan PHPViewing the session IDIf you have an application where the session data does not seem to beaccessible from one page to the next, it could be because a new session isbeing created on each page.To check for this, compare the session ID (the last few characters of the valuewill suffice) to see if it is the same. You can see the sessions ID by viewing thesession cookie as it is sent or by using the session_id() function:echo session_id();Establishing session variablesSession variables are available as soon as youve established them. So,unlike when using cookies, you can assign a value to $_SESSION[var]and then refer to $_SESSION[var] later in that same script. Deleting Session Variables Pengaturcaraan PHP 19
  20. 20. Pengaturcaraan PHPWhereas a cookie system only requires that another cookie be sent todestroy the existing cookie, sessions are more demanding, since there areboth the cookie on the client and the data on the server to consider. Todelete an individual session variable, you can use the unset() function(which works with any variable in PHP):Pengaturcaraan PHPTo delete every session variable, reset the entire $_SESSION array:$_SESSION = array();Finally, to remove all of the session data from the server, usesession_destroy():session_destroy();Note that prior to using any of these methods, the page must begin withsession_start() so that the existing session is accessed. Lets delete asession. 20
  21. 21. Pengaturcaraan PHP Step 2 Invoke the session.Pengaturcaraan PHPStep 4Destroy all of the session material. 21
  22. 22. Pengaturcaraan PHPDeleting one variableTo delete just one session variable, use unset($_SESSION[var]). Changing Session BehaviorPengaturcaraan PHP 22
  23. 23. Setting Example Meaningsession.auto_start 0 If sessions should be automatically used (0 means no).session.cookie_domain www.mycompa The URL wherein the session cookie should be accessible. ny.comsession.cookie_lifetime 0 How long, in seconds, the session cookie should exist (0 means for the life of the browser).session.cookie_path / The domain path wherein the cookie should be accessible.session.cookie_secure 0 Whether or not the cookie must be sent over a secure connection (0 means no).session.gc_maxlifetime 1440 The time period in seconds a session should PHPSESSID The name given to all sessions.session.save_path /tmp Where session data will be stored.session.serialize_handler php What method should be used to serialize the session variables. Whether or not the session ID should be stored in a cookie (0session.use_cookies 1 means no). Whether or not the session ID must be stored in a cookie (0 meanssession.use_only_cookies 0 no). Whether or not PHP should add the session ID to every link in ansession.use_trans_sid 0 application (0 means no). Pengaturcaraan PHP Each of these settings, except for session.use_trans_sid, can be set within your PHP script using the ini_set() function: ini_set (parameter, new_setting); For example, to change where PHP stores the session data, use ini_set (session.save_path, /path/to/folder); 23
  24. 24. Pengaturcaraan PHPTo set the name of the session (perhaps to make a more user-friendly one),you can use either ini_set() or the simpler session_name() function. The benefits of creating your own session name are twofold: its marginally more secure and it may be better received by the end user (since the session name is the cookie name the end user will see). That being said, for session_name() to work, it must be called before every use of session_ start() in your entire Web application. Lets rewrite the example with this in mind. Pengaturcaraan PHP Sessions have the following advantages over cookies They are generally more secure (because the data is being retained on the server). They allow for more data to be stored. They can be used without cookies Whereas cookies have the following advantages over sessions: They are easier to program. They require less of the server. 24
  25. 25. Using Sessions without Cookies Pengaturcaraan PHPPengaturcaraan PHPYou can use sessions without cookiesby passing along the session nameand ID from page to page. This issimple enough to do, but if you forgetto pass the session in only oneinstance, the entire process is shot. 25
  26. 26. Improving Session SecurityPengaturcaraan PHPStoring the session ID in a cookie isconsidered the more secure method ofusing sessions, as opposed to passingthe session ID along in URLs or storingit in hidden form inputs. Thosealternatives are less secure becausethe session could easily be hijacked byanother user.If a malicious user can learn anotherusers session ID, he can easily trick aserver into thinking that it is his sessionID. At that point he has effectively takenover the original users entire sessionand may have access to her data. Sostoring the session ID in a cookiemakes it somewhat harder to steal. 26
  27. 27. Pengaturcaraan PHPOne method of preventing hijacking is to store some sort of user identifier inthe session, and then to repeatedly double-check this value.HTTP_USER_AGENT — a combination of the browser and operating systembeing used — is a likely candidate for this purpose. This adds a layer ofsecurity in that a malicious user could only hijack another users session if heis running the exact same browser and operating system.For example, a login page would have the following:Pengaturcaraan PHPStep 3After assigning the other session variables, store HTTP_USER_AGENT.HTTP_USER_AGENT is part of the $_SERVER array. It will have avalue like Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0; .NETCLR 1.1.4322). This variable is run through the md5() function, whichwill turn it into a 32-character hexadecimal hash (although its justeasier to say that the data is encrypted). 27
  28. 28. Pengaturcaraan PHPStep 6Change the !isset($_SESSION[user_id]) conditional to the following: End Pengaturcaraan PHP 28