You are on page 1of 2

Creating Your First PHP Cookie When you create a cookie, using the function setcookie, you must

specify three arguments. These arguments are setcookie(name, value, expiration): 1. name: The name of your cookie. You will use this name to later retrieve your cookie, so don't forget it! 2. value: The value that is stored in your cookie. Common values are username(string) and last visit(date). 3. expiration: The date when the cookie will expire and be deleted. If you do not set this expiration date, then it will be treated as a session cookie and be removed when the browser is restarted. In this example we will be creating a cookie that stores the user's last visit to measure how often people return to visit our webpage. We want to ignore people that take longer than two months to return to the site, so we will set the cookie's expiration date to two months in the future! PHP Code: <?php //Calculate 60 days in the future //seconds * minutes * hours * days + current time $inTwoMonths = 60 * 60 * 24 * 60 + time(); setcookie('lastVisit', date("G:i - m/d/y"), $inTwoMonths); ?> Don't worry if you can't follow the somewhat involved date calculations in this example. The important part is that you know how to set a cookie, by specifying the three important arguments: name, value and expiration date. Retrieving Your Fresh Cookie If your cookie hasn't expired yet, let's retrieve it from the user's PC using the aptly named $_COOKIE associative array. The name of your stored cookie is the key and will let you retrieve your stored cookie value! PHP Code: <?php if(isset($_COOKIE['lastVisit'])) $visit = $_COOKIE['lastVisit']; else echo "You've got some stale cookies!"; echo "Your last visit was - ". $visit; ?> This handy script first uses the isset function to be sure that our "lastVisit" cookie still exists on the user's PC, if it does, then the user's last visit is displayed. If the user visited our site on February 28, 2008 it might look something like this: Display: Your last visit was - 11:48 - 02/28/08

Using Session to Attain State: HTTP is inherently stateless, which means that each request from a browser is independent of any prior request. In other words, the server remembers nothing about the client between requests. PHP uses a Session variable to overcome this, allowing information to be tracked (i.e., for the server to remember state information). Retaining state means telling the server about variables that were set some time during the current use of the website. By convention, the server will keep track of a user for a limited time, set by the server; usually this is 10 to 20 minutes, after which the server stops tracking. If the

user does anything in that session period, the time starts over for another 10 or 20 minutes. This is why I can't log into my electronic account at the bank, have lunch, and still find myself logged in when I come back; the server will tell me that I have "timed out" and that I should go back and log in again (starting another session). How does a session work? A Session depends on a unique id, generated by the server, which provides access to session variables stored on the server. The id is passed back and forth to the client as a short-lived cookie (or else it is attached to a URL querystring). The id is visible to the client, but session variables are not because they are stored on the server. Cookies. A cookie is a short bit of text sent by the server and stored on the client. It contains a name : value pair and usually an expiration date (optional). When the browser connects to a URL, it searches for URL-specific cookies, and if there are any, the contents of the cookie (name, value pairs) is sent to the server. Setting Cookies with PHP. You can set a cookie using setcookie ('cookie_name', 'cookie_value'). You an access the cookie from the cookie collection as $mycookie = $_COOKIE['cookie_name'], which will assign whatever value was set. Cookies with Sessions. When you use a Session, PHP automatically sets a cookie for the session ID. The Session ID is also stored in a constant, SID. If you want a copy of the cookie contents set up this way, session_get_cookie_params( ) will retrive them. It is also possible to include the session ID as part of the page URL. This can be done, using a setting established by the server administrator (see p. 512) (off by default). It can be done manually as <a href="my_page.php?<?php echo strip_tags(SID); ?>">, or, alternatively, <a href="nextpage.php?<?php echo htmlspecialchars(SID); ?>">click here</a>. Running a Session There are four steps in using a session: 1. Startingsession_start ( ) 2. Registering Session Variables$_SESSION['my_session_variable_name'] = $some_value; 3. Using Session Variables$variable_to_use = $_SESSION('my_session_variable_name'] The text suggests that you check to see whether this variable has been set, using if ( isset ($_SESSION['my_session_variable_name;])) ... . 4. FinishingUnset and end the session using unset($_SESSION['my_variable_that_I_used'] and session_destroy(); Example The example on 514-517 goes through these four steps, starting a session and setting a session variable on one page, then starting a session (again) and retrieving the variable on a second page, and then ending the session on a third page. Implementing Authentication with Session Control A second example, pages 517-524, uses a session variable for page authentication. This is very standard practice (which you will do in assignment 8). Authentication begins with a login, usually a request for an id and password that is matched to a database table of previously approved authenticated users (people who are allowed to see this page). If there is a match, the user id (or any other string) is stored in the session variable, as $_SESSION['authentication']=$userid; if they are not in the database, they are given a message and options ("Restricted Access: Login or go away..."), and another shot at the login form, usually. Study Listing 23.4, which is complicated (we'll do this in class). After a successful login (id and pw found, session authentication variable set), each page includes a small block of code to start a session and check the session authentication. If the authentication is set ( if (isset ($_SESSION['authentication']) ) the page is displayed; otherwise, an error message and a link to the login page is displayed.

You might also like