|Cookies - A Tutorial by Kyle McIntyre
First time here? Welcome to the site! A log of this visit has been recorded using cookies. Refresh the page to see cookies in action!
Cookies are set in PHP via the setCookie()
function. The function has six parameters that correspond to the attributes described in the first section of this tutorial. However, only the first (name) parameter is required. Refer to the formal documentation for a more thorough treatment of the parameter list. One thing to note is that the function expects the expiration date in the form of a Unix timestamp.
Cookies are retrived in PHP via the $_COOKIE or $HTTP_COOKIE_VARS arrays. For instance, if you set a cookie with the name my_cookie
, then you would retrieve the cookie by referencing $_COOKIES['my_cookie']
. Note that the $_COOKIES syntax is only available as of PHP 4.1.0. If you have register globals turned on, the cookie will automatically be in scope under the variable name $my_cookie
Cookies in PHP
class, which is part of the javax.servlet.http library. There is no need to import the Cookie class when developing JSP applications because the entire javax.servlet.http library is available by default. The Cookie class expects two string parameters in its constructor, corresponding to the cookie's name and value, respectively. The cookie may be further defined by using the setPath, setMaxAge, and other member functions of class Cookie. The most notable of these functions is setMaxAge, which allows the developer to specify the cookie's timestamp. However, unlike PHP where you provide an absolute timestamp, Java expects a relative measurement. If the age is set to a negative number, then the cookie becomes a session cookie and will expire automatically when the session ends. If the age is set to zero then the cookie will be deleted on the user's machine. Once a Cookie object has been instantiated, it must be added to the server's response to the webpage request. This is accomplished by calling response.addCookie(). Thus, a typical cookie in JSP might look as follows:
Cookie name_cookie = new Cookie("name", "Kyle McIntyre");
name_cookie.setMaxAge(24 * 60 * 60); // Will last for 1 day
In order to extract cookie values from an HTTP request in JSP, it is necessary to call request.getCookies()
, which returns an array of Cookie objects or null if no cookies were received. The cookie may then be examined, modified, and potentially reused.
// Store "Kyle McIntyre" in a cookie called name_cookie.
var name = "Kyle McIntyre";
document.cookie = 'name_cookie=' + escape(name) + 'expires=Thu, 9 June 2005 20:00:00 UTC;';
Last Updated: June 8th, 2005