Cookies are pieces of data that are stored as
simple little text files in the site visitor's computer, and allow the
site server to keep track of what a visitor is doing during their visit.
You are probably familiar with cookies from your time with our HTML tutorials
(or from your experience with HTML), but just to recap, cookies are pieces of
data that are stored as simple little text files in the site visitor's computer,
and allow the site server to keep track of what a visitor is doing during their
visit (or even across multiple visits.) Some people think of cookies as
bad or evil things, because they are sometimes used by advertisers to track an
individual's browsing habits. Any decent anti-spyware program can
prevent that kind of thing, however, and cookies are a useful and necessary
mechanism for such things as personalized sites (where you first log in, and are
then presented your personalized version of the site), shopping carts and the
like.
Creating a Cookie
PHP provides full support for cookies. Creating a cookie is a simple
matter, but there is an important timing consideration to remember. If you
are going to send a cookie down to the user's system, you must send it down
before you send anything else; before any part of the page itself is sent, even
before a blank line! A cookie is sent by using the setcookie( ) function.
Here's an example:
<?php
setcookie ("cookiename", "This text will be in the cookie");
?>
<html>
<head> ....... etc.
Here you can see a cookie being sent with the name "cookiename" and
containing the value "This text will be in the cookie". Also, you can see
that it is sent before ANY of the HTML code on the page itself is sent.
You can send more than one cookie, if you need to, by using more setcookie( )
function calls, but remember that the protocol has a limit of twenty cookies
from one site to a single user.
Reading a cookie
When a user visits a PHP page that could read a cookie that is present in the
user's computer at the time they call for the page, PHP automatically reads the
cookie into a variable named the same as the cookie, but prefixed with a $ sign.
(Note that for this reason you should follow PHP variable naming conventions
when creating your cookies - no spaces, for example!) So, to read our
cookie, we would simply reference it's variable name like this:
<?php
print "our cookie says $cookiename";
?>
This would show up on the page as:
our cookie says This text will be in the cookie
Simple enough!
Deleting a cookie
When cookies are created, they are set by default to be deleted when the user
closes their browser. You can override that default by setting a time for
the cookie's expiration like this:
<?php
setcookie ("cookiename", "This text will be in the cookie", time( ) + 3600);
?>
<html>
<head> ....... etc
The addition of the
time( ) parameter followed by a plus sign and a number of seconds sets the
amount of time from now at which point the cookie is to expire. In our
example, the cookie will expire one hour from now.
There may be occasions
when you need to delete a cookie before the user closes their browser, and
before its expiration time arrives. To do so, you would use the setcookie(
) function with the appropriate name for the cookie and with a time( ) parameter
with a negative number, like this:
<?php
setcookie ("cookiename", "", time( ) - 1);
?>
Notice that we have left
the contents parameter in its proper place, but with nothing in it.
Remember also that the setcookie( ) function call has to come before anything
else on the web page.
Being able to manipulate
cookies, we will now be able to manipulate information within a user's session,
remembering it from page iteration to iteration, and from page to page.
There is a relationship between Sessions and Cookies -- they serve somewhat
the same purpose, and are, to a certain extent, usable interchangeably.
Sessions, which were integrated into PHP in version 4 of the language, are a
means to store and track data for a user while they travel through a series of
pages, or page iterations, on your site.
The most significant differences between the two are that cookies are stored
on the client, while the session data is stored on the server. As a
result, sessions are more secure than cookies (no information is being sent back
and forth between the client and the server) and sessions work even when the
user has disabled cookies in their browser. Cookies, on the other hand,
can be used to track information even from one session to another by setting
it's time( ) parameter
How Sessions Work
Sessions in PHP are started by using the session_start( ) function.
Like the setcookie( ) function, the session_start( ) function must come before
any HTML, including blank lines, on the page. It will look like this:
<?php
session_start( );
?>
<html>
<head> ....... etc
The session_start( )
function generates a random Session Id and stores it in a cookie on the user's
computer (this is the only session information that is actually stored on the
client side.) The default name for the cookie is PHPSESSID, although this
can be changed in the PHP configuration files on the server (most hosting
companies will leave it alone, however.) To reference the session Id in
you PHP code, you would therefore reference the variable $PHPSESSID (it's a
cookie name; remember that from Cookies?)
Your sharp mind may be
wondering what happens when you come to the second pass through your page and
reach the session_start( ) function again. PHP knows that there is already
a session on progress and so ignores subsequent instances of the session_start(
) -- phew!!
Using Session Data
Having established a
session, you can now create, store and retrieve information pertaining to that
session. You might want, for example, to keep track of items in your
visitor's shopping cart. Information for sessions is stored in a special
directory on the server; the path of that directory is specified in the server's
PHP configuration files.
Information to be stored
for a session is kept in session variables. Session variables are created
by registering them for the session, using the session_register( ) function.
To use that information (on any page iteration in the session) you simply
reference the variable just like you would any other variable. Here's an
example:
<?php
session_start( );
?>
<html>
<head>
<title>Using a session
variable</title>
</head>
<body>
<?php
print "Welcome to
session number: ";
print $PHPSESSID;
?>
<br />
<?php
session_register("username");
$username = "Goody";
print "Your name is: ";
print $username;
?>
</body>
</html>
In this example we have
created a session and displayed the session number. We then registered a
session variable called username (notice the quotes around the variable's name
in the call to the session_register( ) function.)
We now have all the
basic tools to establish a session, and to create and use variables that last
through the entire duration of the session.
Having created a session and saved session data for use across iterations of
pages within a session, we can see that there would be one more very useful
capability. What if we could save session information from one session to
another, returning to information that was saved perhaps a few days ago?
PHP provides this capability by enabling you to save session information in a
file.
A particularly useful example of the application of this ability, is to
capture and refer to username and password information. You could, for
example, create a login page where a visitor can enter their user Id (their
email address, perhaps) and their password, You would then retrieve
session information from an earlier session, based on their user Id, and present
them with customized views of the rest of your site, based on other stored
session variables that you retrieve from the file. Such a project would,
of course, require a little more code that is shown in this tutorial, but the
methods used to save and retrieve the session data are right here!
Another great example of the use of this feature is in conjunction with a
shopping cart. Suppose you have a shopping cart that builds an order as
the user makes their selections and stores that information somewhere based on a
unique identifier such as a combination of their user Id and the session number.
Now suppose their connection is interrupted and their session is lost. If
you had saved their original session information in a file, then when they
reconnected and logged back into your site, you would have all the information
you would need to retrieve their partially completed order. That would
make for a happy shopper!
And so to the technique, which is simple enough: we're going to use the fopen
function to open our file, the session_encode function to encode our session
information into a string, the fputs function to write it into our file and the
fclose function to close the file. Here's an example:
<?php
session_register("username");
session_register("password");
session_register("ordernumber");
$username = "Goody";
$password = "mypass";
$ordernumber = "1234";
$sessionfile = fopen("sessionfile.txt", "w");
fputs($sessionfile, session_encode( ) );
fclose($sessionfile);
?>
As you can see, we are creating three session variables to hold the
information we will need and, in this example, are simply populating those
variables from text strings. You can see here that in the fputs instruction we are using
the session_encode function to take all our session information (which includes
all our session variables, but does not include the session number) and encode
it into a string which becomes the information we write (fputs) to our file.
Now that we have our information safely tucked away, we need a method to
retrieve it again when we need it. For this, we'll use the fgets function
to get the record and the session_decode to retrieve the session information
from the record returned. Here we go:
<?php
session_start( );
?>
<html><head> ....... etc.
<?php
$sessionfile = fopen("sessionfile.txt", "r");
session_decode(fputs($sessionfile, 4096) );
fclose($sessionfile);
?>
There are a couple of things to notice here. First, you'll see that
we started a new session because we need to have an active session to be able to create
the session_variables, which is what the session_decode is going to do.
Next you'll notice that the session_encode and session_decode instructions
are written the other way round from each other, with respect to their
associated fputs and fgets functions. Think of it like this: when writing,
we want to write the result of the session_encode so the fputs contains the
session_encode; when reading, we want to decode the result of the fgets
function, so the session_decode contains the fgets. (Technically, it may
be inaccurate to speak of one "containing" the other, but it certainly helps to
think of it that way!)
Another thing to watch
out for is the scope of our variables.In the first example above, we have specific
statements to define the session variable, so their scope may be more obvious,
but in the second, the variable will be defined by the session_decode function
and so the scope might not immediately occur to you. In either case, if
the definition of the variable occurs within a function (that is, you have
written these instructions inside some function) the scope of the
session_variables will be local to that function. If that's not what you
want, you would have to add the "global" parameter. In the second example
above, this would mean adding a global definition for the variables prior to
invoking the session_decode function, like this:
$sessionfile =
fopen("sessionfile.txt", "r");
global $username, $password, $ordernumber;
session_decode(fputs($sessionfile, 4096) );
fclose($sessionfile);
Finally, you might want
to think a little about the file name you use. In these examples we used a
file called "sessionfile.txt". It might be more useful to you to name your
file something else, such as the user Id, or a combination such as the user Id
and an application identifier (for example, "vincebarnesorders.txt") so that you
will know which file to get your session information from when the user comes
back into your page.
|