340 likes | 694 Views
Maintaining State in PHP. Bryan Duggan. What is meant by state?. To maintain state means the ability to retain values of variables and to keep track of users who are logged into the system. What does it mean to say: "HTTP is a stateless protocol"?
E N D
Maintaining State in PHP Bryan Duggan
What is meant by state? To maintain state means the ability to retain values of variables and to keep track of users who are logged into the system.
What does it mean to say: "HTTP is a stateless protocol"? Hint: How does HTTP compare to FTP or telnet?
What does it mean to say: "HTTP is a stateless protocol"? • HTTP does not keep track of a connection like FTP and telnet do. • HTTP does not provide a way to tell if two requests are from the same user (or are otherwise related).
In what situations is it helpful to keep track of state? • Authentication • Transactions (e.g., shopping cart) • Preferences
Methods for maintaining state • Cookies • Sessions • Passing [hidden] variables • URL Rewriting
What is a cookie? Cookies are simple text strings of the form of name=value which are stored persistently on the client’s machine. A URL is stored with each cookie and it is used by the browser to determine whether it should send the cookie to the web server.
What is a cookie? • "A small piece of information that scripts can store on a client-side machine" • Can set in HTTP header Set-Cookie: NAME=VALUE; [expires=DATE;] [path=PATH;] [domain=DOMAIN-NAME;] [secure] • Creates cookie called NAME with the value VALUE Example: ppkcookie1=testcookie; expires=Thu, 2 Aug 2001 20:47:11 UTC; path=/ http://wp.netscape.com/newsref/std/cookie_spec.html
Cookies • When browser connects to URL, it first checks for relevant cookie • If it finds a cookie for the URL the browser sends the cookie info to the server with the HTTP request • Can use setcookie function in PHP Note: cookie headers must be sent before any other headers or they won't work
Problems with Cookies • Some browsers don't accept cookies • Some users disable cookies
Cookie Example <?php $count++; setCookie(“count”, $count); ?> Welcome! You’ve seen this site <?php print($count . ($count == 1 ? “ time!” : “ times!”)); ?>
Common Pitfalls • Can’t call setCookie() after output has been sent to the browser • Can’t have more than 20 cookies/server • Cookies ONLY persist until the browser closes UNLESS you specify an expiry date: set Cookie(“name”, $value, time() + 3600);
Cookies in JavaScript • You can also manipulate cookie values in JavaScript using these three functions:
Create a cookie function createCookie(name,value,days) { if (days) { var date = new Date(); date.setTime(date.getTime()+(days*24*60*60*1000)); var expires = date.toGMTString(); } else var expires = ""; document.cookie = name+"="+value+expires+"; path=/"; }
Read a cookie function readCookie(name) { var nameEQ = name + "="; var ca = document.cookie.split(';'); for(var i=0;i < ca.length;i++) { var c = ca[i]; while (c.charAt(0)==' ') c = c.substring(1,c.length); if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length); } return null; }
Erase a cookie function eraseCookie(name) { createCookie(name,"",-1); }
Sessions Sessions are just like cookies, except they store the user’s data on the web server. Every request has a unique session id.
PHP Sessions • Provide a way to keep state information • Store values in session variables • Contents of session variables stored on server • Session ID is stored on client • "cryptographically random" number • Stored in URL or • Stored in cookie
Using sessions in PHP • Start a session • Register session variables • Use session variables • Deregister variables and destroy session
Start a session session_start(); • Checks to see if a session already exists • YES: load registered session variables • NO: creates a session and provides access to $_SESSION superglobal • Call at beginning of all scripts that use sessions
Register session variables $_SESSION['myvar'] = 5; • As of PHP 4.1, can register using $_SESSION • Prior to 4.1, used session_register() function (now deprecated)
Use session variables • Access variables by using variable name to index into $_SESSION $_SESSION['myvar'] = 5; • Can access session variables directly if register_globals is on Remember that variables can be set by the user via GET or POST
Unset variables and destroy the session unset($_SESSION['myvar']); • Do not unset the whole $_SESSION array • To unset all session variables at once: $_SESSION = array(); • When finished with a session: session_destroy();