1. PHP intro
  2. PHP basics
  3. PHP variables
  4. PHP functions
  5. PHP conditions
  6. PHP loops
  7. PHP arrays
  8. PHP classes & objects
  9. PHP strings
  10. PHP forms
  11. PHP entities
  12. PHP files
  13. PHP include files
  14. PHP date & time
  15. PHP cookies
  16. PHP databases
  17. PHP sessions
  18. PHP summary

PHP cookies

In web programming, the term 'cookie' means something totally different from what it is popularly known as. In web programming, a 'cookie' is a small text file stored on a users hard drive by a website for various purposes such as remembering a user who frequents that website.

This tutorial focuses on:

Setting a cookie

The function used to set a cookie is setcookie(). A cookie must be sent along with the HTTP headers before any other code. This means that when using the setcookie() function it must be declared first thing on the page - even before the <HTML> tag used in the HTML code. If setcookie() is not the first thing on the page, then the function will fail, a cookie will not be set, and the function will return false! When a cookie is successfully sent, the function returns true.

Syntax of the setcookie() function:
setcookie(name, value, expirationDate, path, domain,isSecure, httpAccess);

The setcookie() function can take seven parameters, but only one is required - the name parameter (to set the name of the cookie).

setcookie() function parameters:

<?php setcookie("cookie1", "this is a cookie"); ?>

The above example will set a cookie named cookie1 that stores the value 'this is a cookie'. This cookie will expire automatically when the web browser is closed since no expiration date is set for it.

Reading data from a cookie

To read data from a cookie, you first have to check if the cookie actually exists. This is achieved through the isset() function. The isset() function is used to check for the existence of a variable, in this case, a cookie variable through the use of the $_COOKIE associative array which stores an array of existing cookies.


If the cookie specified in the isset() function exists, then the function will return true, otherwise it will return false.

<?php if (isset($_COOKIE['cookie1'])) { $cookie1 = $_COOKIE['cookie1']; } ?>

In the above example, an if statement checks for the existence of a cookie named cookie1. If it exists, then its value will be passed to the variable $cookie1. If it does not, then it will remain empty. The isset() function checks for this.

© Copyright 2013-2014
Terms of use | Privacy policy | Copyright information