Using Cookies in PHP

4.01 (905)

Introduction to Cookies

Cookies are one of the most widely misunderstood concepts of Internet surfing to both users and developers. Many people think that cookies are dangerous, insecure 'things' that let people get your credit card details and what not. This is, for most cases, completely untrue. To the experienced web developer, cookies present a medium for allowing quicker and more user friendly access to your website.

Cookies are simply files stored in a special temporary location determined by your web browser (like Internet Explorer) which allow public information to be stored for your benefit usually. By public information, this can entail any information that you have entered into forms on websites, or certain non-identifying information such as your IP address or user agent.

What makes cookies so special is that, sites can set cookies holding your username and password so that you don't have to log in again. Or perhaps they will store your email address and favourite colour so that a website can change its colour so that it is more appealing to you. Most importantly though, is that other websites and people cannot access your cookies, hence making them fairly secure.

Having a secure method to store user information doesn't mean that you can store anything in cookies though. It is widely accepted that you never store a user's credit card number in a cookie, or a password that will give access to a highly secure area (such as online banking). For areas that require less security like forums, web-mail and unimportant user accounts, it is acceptable to store passwords in encrypted form. The topic of encrypting passwords will be discussed later.


How to Set Cookies


PHP has a very handy function for us called setcookie(), which does exactly as it says; sets a cookie. The function contains many different parameters, of which almost all are optional, however, a majority are quite important.

bool setcookie ( string name [, string value [, int expire [, string path [, string domain [, bool secure]]]]] )


This function definition shows us that only the name parameter is actually required, however, to do anything useful, we will be using value, expire and sometimes path and domain.

When you set a cookie, you must give it a name and you should give it a value, unless you are removing it. Cookies are also generally set to expire at a certain time (measured in seconds from 1972). This means, after a certain amount of time, a cookie will be deleted and the information lost. This is a means to remove redundant information from your system and to keep everything up to date. A cookie also has to be set for a particular domain and path. This means you can set cookies to only work in certain directories or sub-domains which can provide added security.

We will now create a very simple example of cookie usage. This is one of the most common methods of using cookies, so this should be quite useful.

First Cookie
<?php
$username 
'jonny4';

setcookie('username'$username);
?>


What we do here, is set a cookie called username containing the username jonny4. Now this cookie will exist in the domain and folder that the script is run in. So we are going to assume you run this script in www.example.com. If you wanted to access it from admin.example.com it would not work, and you will find that the cookie does not exist. However, it is possible to access the cookie from www.example.com/test/cookies/ as this is still in the correct domain.

As this cookie does not have an expiry time, then the cookie will be deleted once the user closes their browser. This can be very useful for keeping a user logged in for an indefinite amount of time, however, as soon as they close their browser (hence, have left the site), the cookie is removed.

There are two very important things to abide by when using cookies. Firstly, there are can be no HTML, text or white-space output before calling the setcookie() function. This is due to a 'protocol restriction' and you will find that header() and session_start() functions must also follow this rule. More information can be found in the Redirecting Users article.

The second rule that you must follow, is that cookie will not become available until the next page has loaded. So you cannot set a cookie, and then immediately access it. You must always first refresh or go to another page to get access to the cookie. This is usually a source of many beginner errors when using cookies, but it is simple to follow.

Accessing the Cookie


Naturally you will want to access the cookie that you have set. With PHP, this is extremely easy and intuitive. Assuming that we have used the above code to set the cookie, and we are now on a new page, we can access the data as follows:

Access the cookie data
<?php

/* Prints the value stored in the username cookie */
echo $_COOKIE['username'];

?>


This code uses the $_COOKIE superglobal to access any cookies set in the current domain. If we were to run this script, it would output jonny4.

It is essential to note that you cannot modify the $_COOKIE superglobal and expect it to update the value in the cookie. If you want to update the cookie, you must manually do it again using setcookie(), again remembering that there can be no output before calling this function.
Rate this article: BAD 1 2 3 4 5   GOOD
Page 1 of 3    >>

Build Your Own Database Driven Website Using PHP & MySQL

  • Installation instructions for Windows, Linux and Mac OS X
  • Instantly apply working code examples from the book to your Website
  • Build a working Content Management System from scratch
  • Master MySQL database administration
  • Fully updated for PHP 5

       Download FREESample Chapters Now!

Ads

PHPNerds Newsletter