PHP cookies above the stateless protocol
HTTP is a stateless protocol. Meaning that once the
clients browsers finishes a transactions with the Web
server the Web server completely looses all recollection of the
transaction. This is, of course, a problem for applications such
as a shopping cart in which a state must be maintained. We need
a way to send information (such as the data from a shopping
cart) and be able to access that data again on all other
subsequent request to that server. The most common approach is
to use sessions via a combination GET and cookies. So
whats a cookie?
Cookies are very small pieces of information (like little
Post-Its if you will) that server side scripting
languages like PHP utilize to store and retrieve information on
the client side. Cookies are tied to a path on the server;
meaning that only the domain that issued the cookie can have
access to this data. All data is stored as a name-value pair.
For Windows NT users the most common place to find your cookies
is here C:\Documents and Settings\your Stuff\Cookies;
youll need to replace your Stuff with the name of your own
personal directory.
Moving forwards with syntax. Before going any further there are
a number of guidelines youll want to remember. Note that
you have to put the actual cookies code before any HTML tag;
including the head, title, body etc. Cookies are bound to their
hierarchical structure meaning any attempts to access a cookie
from above its own hierarchy would fail, hence it is best to
place the cookie in a file located within the root directory.
This will allow you to access the cookie from anywhere on the
site. Also, cookies will not become visible until the next
loading of the page. Another thing I should mention is cookies
cant exceed 4KB. Doing so just confuses the Web
server and forces it to generates a fatal error like the one
here.
Bad Request
Your browser sent a request that this server could not
understand.
Size of a request header field exceeds server limit.
Moreover browser can only accept up to 20 cookies per domain
(300 cookies in total) if the maximum number of cookies is met
the browser will delete the least recently used.
Heres the code.
<?php
setcookie(cookie, hello
world);
?>
setcookie is how we define cookies. This function has a
number of parameters (bool setcookie ( string name [,
string value [, int expire [, string path [, string domain [,
bool secure]]]]] )). I wont go over all of them; however I
do think its important we discuss the first three.
string name.
<?php
setcookie(cookie);
?>
The first parameter (name) is a string value; you should name
this something relevant.
string value.
<?php
setcookie(cookies, hello
world);
?>
The second parameter (value) is a string value. Pretty
self-explanatory, you recall me saying that all data is stored
as a name-value pair. Without a value what would be the point
anyway?
int expire.
<?php
setcookie(cookies, hello world,
time() + 3600);
?>
The third parameter (expire) is an integer value. We can set
this by using the time function (int time (
void )). This returns the current time measured in the
number of seconds since the Unix Epoch. Once we know what time
it is we simply add to this the number of seconds we want for
the cookie to live. If the parameter is set the cookie lives up
to this date. This is known as a persistent cookie. On the other
hand if no expiration date is set a so-called session cookie is
generated. Session cookies work just the same only they expire
once the browser is closed. Needless to say the current time is
the state pertaining to the clients own time settings (you have
no control over that). So if the client has the wrong date this
cookie might expire prematurely. In our example we simply take
the current time and add 3600 seconds more; that is to say the
cookie will expire 1 hour from the current time. Once you get
the hang of it you can start getting fancier maybe add a little
JavaScript to determent the users actual date setting etc,
etc.
On the next loading of this page or any other page on the same
directory or sub directories we can access the cookie as
follows.
<?php
echo $_COOKIE["cookie"];
?>
Cookies are great for storing simple name-value pairs but how
do you store multiple variables. A common approach is to simply
treat the cookie as an array; unfortunately this technique just
isnt practical given that each element in a cookie array
is treated as one cookie which brings us right back to the 20
cookies per domain only rule.
A better solution is explode (array explode
(string separator, string)). This function returns an array
by splitting a string on boundaries formed by a string
separator. Heres an example.
<?php
$airplanes =
$fuselage.','.$wings.','.$cockpit.','.$fuel.','.$passengers;<
/i>
setcookie(modernMarvels , $airplanes, time()
+ 3600);
?>
The preceding code assigns five variable values to a cookie in
the form of a string. Next explode uses a comma (or any
other punctual mark as a string separator) to access each value
individually converting string to array. Now all that is left is
looping through the array.
<?php
$myvars =
explode(,,$_COOKIE[modernMarvels]);
$foreach($myvars as $value)
{
echo $value;
}
?>
The final thing is how to delete cookies. One way is to send a
cookie with the same name setting its value to an empty string.
Intuitively the latter replaces the former however the cookie
still subsist; hence a better way is to additionally send a
cookie with the same name but with an expiration date that is in
the past. Think of this like a little terminator sent from the
future back in time to kill itself. Cool hu? For example if you
want to delete a cookie called
unstoppableCyborg heres what you do.
<?php
setcookie(unstopableCyborg, ,
time() 3600);
?>
Well that about wraps it up here. If you wan to see real
multiple value cookies in action simply visit our website www.foamerstudios.com and
try adding a few Website templates to our favorites list
application. Every single template selection you make will be
stored on your machine via cookies. To learn more about cookies
visit the preliminary specification guide at htt
p://wp.netscape.com/newsref/std/cookie_spec.html
About the author:
Dave Collado is a senior design consultant at www.foamerstudios.com. Our
studio offers quality website templates, template customization,
flash templates, phpnuke themes, phpbb themes, osCommerce
templates, SWiSH templates, icon sets, web design tutorials, and
many other web design and web hosting services.