Login | Contact Us | Site Map | Resources

PHP Form Handling & Browser Interaction

Home > PHP Tutorial > PHP Cookies

PHP Cookies

Cookies are small files that are stored in the visitor's browser.Cookies can be used to identify return visitors, keep a user logged into a website indefinitely, track the time of the user's last visit, and much more.

Cookies accept seven different arguments, but only the "name" is required. (Keep in mind that all values are stored on the visitor's computer, so the data is not private. Never store passwords in cookies, for example!) The options are:

Argument Description
name Name of the Cookie
value Value of the Cookie
expire Time When Cookie Expires (Unix Timestamp) (If "0", Or Omitted, Cookie Will Expire When Browser Closes) (Set to Client's Time, Not Server's)
path Server Path Where Cookie Is Available (If Path Is the Root Directory, Cookie Is Available In Entire Domain) (Default Value Is Current Directory)
domain Domain That Cookie Is Available
secure Indicates That Cookie Should Only Be Transmitted Over a Secure HTTPS Connection From Client
httponly When TRUE, Cookie Is Only Accessible Through HTTP Protocol

PHP allows you to create, retrieve and update cookies. The setcookie() function is used to first create a cookie. This function must be run before any other data is sent to the browser, such as the opening <html> tag or random whitespace. The syntax is: setcookie(name, value, expire, path, domain);

<?php
  setcookie("Example", "Whatever Value I Want", time()+2592000);
?>

Here we have set a cookie called "Example" that has a useless value of "Whatever Value I Want" and an expiration date one month in the future. (We have not yet studied php date and time functions, so I will briefly clarify that the time() function collects the current timestamp and adds 2591000 seconds to it, which is 30 day's worth of seconds, thus creating an expiration date 30 days in the future.)

Now, we are free to retrieve the "value" that is stored in our cookie, using the $_COOKIE superglobal. It is best to use the isset() function for this, because if a cookie has not been set on the computer that we are trying to retrieve it from, headaches can result.

<?php
  if (isset($_COOKIE["Example"])) {
    echo $_COOKIE["Example"];
  } else {
    echo "No Cookie Named 'Example' Is Set";
  }
?>

Here we check to see if the cookie that we created really was created, and echo the value if it was. The value that will be echoed is "Whatever Value I Want". A more practical example might have stored the user's name or preferences, but it's fun to be unpredictable.

Deleting a cookie is as simple as using the setcookie() function with an expiration date in the past. Since there are 3600 seconds in an hour, using -3600 will set the expiration date an hour previous and the cookie will expire and disappear.

<?php
  setcookie("Example", "", time()-3600);
?>

Finally! A cookie that your mother won't limit your intake of!