PHP
PHP introduction
PHP basics
PHP variables
PHP functions
PHP conditions
PHP loops
PHP arrays
PHP OOP
PHP strings
PHP forms
PHP entitites
PHP files
PHP include files
PHP date and time
PHP cookies
PHP databases
PHP sessions
PHP summary

Programming

Programming intro
Java

Markup

First webpage guide
HTML
XHTML

Browser scripting

Javascript
VBScript
AJAX

Server scripting

ASP

Making money online

Make money online

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 lesson 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:

Example:

<?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.

Syntax:

isset($_COOKIE['nameOfCookie']);

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

Example:

<?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 a cookie named cookie1 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.

Practice

Online code editor
Practical examples
Practical exercises
Step-by-step tutorials

Reference

Terms glossary
Reference material

Rate this site

Rate this site
Visitor comments