T-XU.COM      
Home |
  Home>Computer Programming>CGI>
PHP and Cookies; a good mix!
By Dennis Pallett        [Hits: 20628]



Introduction Cookies have long been used in PHP scripts,and are a very useful function. But what exactly are cookies?Maybe you have used then, but you still don't know exactly whatthey are. Or you are completely new to cookies? It doesn'tmatter, because in this tutorial I will show you exactly whatcookies are, and what they are used for.

Cookies in a nutshell Cookies are small pieces ofinformation that is stored on the computer of your visitors.Each browser handles it differently, but most simply store theinformation in a small text file. Internet Explorer has aspecial folder, which can be found in your C:Windows orC:WindowsSystem32 folder. You can delete all your cookies, bygoing to the Options and 'Clearing Cookies' or deleting them byhand. I don't recommend this though.

Almost every website uses cookies. If you go to Amazon.com, youwill get several cookies. The same goes for CNN.com. Even Googleuses cookies! They are extremely useful for (temporarily)storing information. For example, if you have a login system foryour visitors, you could save their userid and password (veryheavily encrypted!) so they are automatically logged in the nexttime they visit your website.

Or you could remember their last visit, and highlight everythingthat is new. And that's just the beginning.

Using Cookies Using cookies in PHP is extremely easy. Infact, there is nothing to it, because of PHP's inbuilt setcookie() function. Have alook at the documentation, and then try the following example:

<?php

// Set a cookie // Cookie name: name // Cookie value: DennisPallett // Cookie expire: in 24 hours

setcookie ('name', 'Dennis Pallett', time() + (60*60*24)); ?>

If you run the code above, then a cookie will be set. That'sall. The cookie name and value are pretty obvious. The cookieexpire is when the cookie expires, or goes away. Simply use thetime() function and add thenumber of seconds you want to have the cookie available to it.In the example I added 60*60*24=86400 seconds, or 24 hours.

If you have looked at the documentation, you probably noticedthere are additional arguments. As the documentation says, thepath is to limit a cookie to a specific path on your web server.This is often used when you run multiple instances of the samescript in separate directories. You can safely omit thisargument when it doesn't matter if the cookie is availablesite-wide.

There is also the domain argument. This can be used to limit thecookie to a specific sub-domain, e.g. test.example.com. You canalso safely ignore this argument, or set it to .example.com(note the beginning period, this is essential!).

Finally, there is also the secure argument. This argument isonly used for cookies that are sent over a secure HTTPSconnection (SSL). Just ignore this argument, unless you'reworking with a secure connection.

One thing that should be mentioned is that cookies must be set,before you display any HTML/text. It's probably best if you turnon output buffering by putting ob_start() at the top of yourpage.

Now that you have set a cookie, you probably want to retrievethe value as well. After all, that is the whole point of usingcookies. Thankfully, as PHP is ever so easy, you can retrievethe same way as you retrieve a GET value. See the followingexample to retrieve the value of the previous example:

<?php echo 'Your name is ' . $_COOKIE['name']; ?>

This should print "Your name is Dennis Pallett".There's nothing more to it. It's just that easy!

Finally, one thing you probably want to do as well is removecookies. This is as easy as setting them. Simply change thevalue of the cookie to FALSE, and change the expire date to-3000 seconds. See the following example:

<?php setcookie ('name', FALSE, time()-1000); ?>

Checking if cookies are enabled Before you start usingcookies, you must make sure your visitor has cookies enabled.This can be done with a simply PHP checking script.Unfortunately, the PHP page needs to reload to check forcookies. But this can be done very transparently, and yourvisitor should hardly notice anything.

The following example will first set a test cookie, then reloadthe page, and finally check whether cookies are enabled.

<?php error_reporting (E_ALL ^ E_WARNING ^ E_NOTICE);

// Check if cookie has been set or not if ($_GET['set'] !='yes') { // Set cookie setcookie ('test', 'test', time() + 60);

// Reload page header ("Location:checkcookies.php?set=yes"); } else { // Check if cookieexists if (!empty($_COOKIE['test'])) { echo "Cookies areenabled on your browser"; } else { echo "Cookies are<b>NOT</b> enabled on your browser"; } } ?>

Run the code above, and see what the output is. Check if cookiesare enabled in your browser. If they're not enabled, then youcan enable them by going to your browser's options.Unfortunately, this is different from each browser, so I can'tgive you exact instructions. But Google can.

Storing Arrays One feature of cookies that is oftenmissed in articles is the ability to story arrays. Cookies canbe used to store multi-dimensional arrays, which can beextremely useful to store data.

Consider the following code;

<?php setcookie ("name[first]", "Dennis",time() + (60*60*24)); setcookie ("name[last]","Pallett", time() + (60*60*24)); ?>

You can then display these two cookies using the following code:

<?php echo "First Name: " .$_COOKIE['name']['first']; echo "<br />Last Name:" . $_COOKIE['name']['last']; ?>

The cookie 'name' is an array, and has multiple values. You caneven go deeper and have multi-dimensional arrays, e.g.$_COOKIE['name']['test']['something']['value']. You could storewhole arrays of data in cookies. But beware that you don't storetoo much data, there are certain size limits to cookies.

In Conclusion... Cookies are really versatile, and can beused for a lot of different purposes. Many websites use cookies,and cookies can really make your website more personalized.Using cookies in PHP isn't hard at all, and you should be ableto use them without any difficulty.

Before actively using cookies in your website, you must checkwhether the visitor has enabled them in their browser. If theydon't have cookies enabled, you must either redirect to anon-cookies version of your website, or you can make sure yourwebsite also works without cookies.

You can download a sample script at http://www.phpit.net/demo/php%20and%20cookies/logger.zip,where cookies are used in a (somewhat) practical way. In thisexample, there is a logging module, called log.php and a displaymodule, called history.php. Basically, you include the log.phpin other PHP pages, and then you can view history.php to lookupall the pages you have viewed and how often. The example usesarrays, and stores them in cookies.

The examples in this article can be downloaded at http://www.phpit.net/demo/php%20and%20cookies/examples.zip.

If you have a really unique practical way of using cookies,please let me know at dennis [AT] nocertainty [DOT] com. I'dreally like to hear about interesting ways of using cookies.
  Top Articles
*CGI Security Issues
*Clever Profit Growth Software
*Why Aren't You Using CGI
*How to Stop Digital Thieves wi
*Open Source Scripts
*5 CGI Scripts You Must Use to
*Quick Intro to PHP Development
*PHP On-The-Fly!
*this is a test
*Screen scraping your way into
*ASP, CGI and PHP Scripts and R
*Better Writing: What Works and
  Related Articles
*PHP On-The-Fly!
*Screen scraping your way into
*Track your visitors, using PHP
*Mastering Regular Expressions
*Autoresponders With PHP
*ASP, CGI and PHP Scripts and R
*Password Protection and File I
*Better Writing: What Works and
*Quick Intro to PHP Development
*Open Source Scripts
*this is a test
*How to Stop Digital Thieves wi


Prev: New Credit Scoring Model Could Help Millions   Next: Tips to Energize Your Presentations



Home | Site Map | Bookmark this site | T-XU RSS
Copyright 2007 T-XU.com - All Rights Reserved Worldwide.