If you're using PHP (and perhaps MySQL with it)
to make as much of your site dynamic as possible, you won't be able to
make a site truly interactive and tailored to individual users unless
you use something more. Something like "cookies."
Using Cookies in PHP
It's got to happen sooner or later. Even if you're using PHP (and
perhaps MySQL with it) to make as much of your site dynamic as
possible, you won't be able to make a site truly interactive and
tailored to individual users unless you use something more. Something
like "cookies."
Cookies, unfortunately, have been
given a bad rap. I once, during an Internet Safety Course, was told
(from a police officer, no less!) that if I visit a site, the owner of
the site could use something called a "cookie" to view my name and
address. I refrained from correcting the officer, but was tempted to.
The statement was very far off.
Cookies are tiny files containing text stored on your computer.
A website can set them, and read from them. They can read different
things about your visit, such as your IP address, or perhaps your
screen resolution. Or, the pages you visited and forms you filled out.
They cannot, however, read your name and address if you don't provide
them with it.
Now that that's out of the way, let's get started. Let's create
a page that sets a simple cookie (name it "setcookie.php", or
"setcookie.php3", depending on your server's settings):
setcookie("user", $username, time()+604800); /* Expires in a week */
This is fairly simple. We're using PHP's built in "setcookie"
function. As you can see, it accepts several arguments. The first
argument, within double-quotes, is the name of the cookie. In this
case, it is "user" - we're storing a username. The second argument is a
variable, obviously given a value beforehand. The third argument
specifies the length that the cookie should be considered "active" -
or, in other words, determines the expiration date at which the cookie
is discarded.
In this case, we have it set to expire in one week. The number
you see there (604800) is the number of seconds in a week, and the text
after the setcookie command is a small comment informing us of how long
it will take for the cookie to expire. Using comments, in this case, is
a very good idea. This way, we don't have to memorize how many seconds
make up a day, a week, or a month.
Here's a small reference on numbers and the amount of time they signify in determining the expiration date/time of a cookie:
One Minute: 60
Ten Minutes: 600
Half-an-Hour: 1800
One Hour: 3600
One Day: 86400
One Week: 604800
Two Weeks: 1209600
One Month (30 days): 2592000
One Year (365 days): 31536000
You can probably work with these numbers to determine how many
seconds are in any given amount of time. Be sure to have a calculator
handy, though! If you lack a real-life calculator, Windows users can
click on their Start Menu, choose "Run", and type in
"CALC."[PAGEBREAK]Using the earlier command, you'll create a cookie,
accessible only on your domain name, with the name "user." This
cookie's value, if called upon, will be whatever the variable $username
holds. You could have just as easily replaced $username with any string
of text to specify the value of the cookie, provided that the string is
enclosed in double-quotes and escapes any inappropriate characters
within.
So, how do we read from a cookie? Well, at times, you can simply
reference the name of the cookie as a variable - in this case, $user.
However, I consider it good practice to specifically grab the value of
the cookie and assign it an appropriate variable - this is useful if
you wish to use one name for the actual cookie, but access it's value
from a variable of a different name. For example:
$user = $HTTP_COOKIE_VARS["user"];
Simple, isn't it? We're using a simple assignment operation to grab the
value of the "user" cookie and give it a name we can use within our
script: $user. You can easily replace $user with $username, $userid, or
$purplebanana - whatever you want.
Now, there will likely come a time where you will want to allow
your users to logout of whatever system you choose to build with your
newfound cookie knowledge. This is almost just as easy as setting a
cookie:
setcookie ("user", "", time()-604800);
This is pretty simple: we have to specify the name of the cookie, as
expected. We do not need to specify any value for the second argument,
as is indicated by the two double-quotes without anything in-between.
After this, we have the usual number of seconds used to set the
cookie's expiration date, with one crucial difference: can you guess
what?
If you noticed the "minus" sign, negating the number after it, then
congratulations, you get a cookie. Any cookie set for an expiration
date that is in the past is discarded. So, technically, we're using the
"setcookie" function, but not to set a cookie. Maybe a tad confusing,
but not a big deal.
As for the number of seconds: we could, if we wanted to, set it
to "-1", and it would probably work just as well. However, due to
possible variances between computer times, dates, and even time zones,
you might as well set it the number of seconds in a week. That way, you
avoid any possible risks, and the extra work is almost non-existent.
A word of warning before I depart: you should always set,
delete, and declare cookie variables before producing any output on
your page - even whitespace. For example, the below code would produce
an error (I've specified the value of the cookie with a string of text
rather than a variable this time, to combine two examples into one):
echo("Welcome to my page...the setcookie command below will not work.")
setcookie ("user", "Bob123", time()+604800);
// Would expire in a week, except it doesn't work
However, this next block of code would work just fine:
setcookie ("user", "Bob123", time()+604800); /* Isn't that better? */
echo("Welcome to my page...a cookie has been created on your computer.<p>" .
"Don't worry, I don't know your address, or your name.")
This applies to almost all references to cookies - so make sure
nothing has been printed to a webpage in any way whatsoever before
reading from, setting, tossing (just kidding), and deleting your
cookies. This includes echo commands, print commands, printf commands,
sprintf commands, or HTML.
Congratulations if you've made it this far (you didn't skip
right to the end, did you? This isn't a whodunit...it'll do you no
good!), you now know how to set cookies, read from them, and delete
them.
|