You are on page 1of 10

Cookies Tutorial

Part 1 - Introduction to Cookies


 Part 1 - Introduction to Cookies
 Part 2 - PHP and Cookies

Introduction
Cookies are a technology which can be easily and simply used by a Webmaster to achieve a great many
very useful tasks when creating websites. Although cookies are well known to users, many people are not
really sure what they are used for, and a large amount of webmasters don't realise the possibilities open
to them when they use cookies. Others have been put off, thinking that they must be difficult to use, but in
reality, cookies can be set and used by a simple command in most scripting languages. In this tutorial I'll
cover setting and using cookies in PHP, JavaScript and ASP, as well as giving some basic information on
how cookies can be used.

What Is A Cookie?
Apart from being a type of biscuit, a cookie is also a very useful piece of technology for use on the web.
One of the problems which many websites need to overcome is that there is no way of directly finding out
who is on a website. Although many details about the user (such as their browser, IP address and
operating system) are available, the use of dynamic IP addresses (which change every time the user logs
on) and IP address sharing (so that many people share the same IP) mean that there is no reliable way of
recognising a particular user when they re-visit a website.

Cookies overcome this problem. They basically give the website owner the opportunity to store a little
piece of information on a user's computer which they can then retrieve at a later date. Cookies are just
tiny text files (only up to 4Kb in size) and a website can write them to the user's computer via the web
browser. The same website can then request the cookie from the user and, if it exists, the value stored
will be reported back to the website. The cookie can persist on the user's computer, staying there if the
browser is closed, the computer is switched off and if the internet connection is changed.

What Use Is A Cookie?


So why would anyone want to store 4000 characters of text on a user's computer? It isn't enough to put
anything really worthwhile on there! The power of the cookie, though, is to recognise a site visitor over
and over again. To give just a few uses of cookies:
 Many portals and search engines use them to provide customized pages and results to their
users, allowing such features as 'My Yahoo' etc.
 Many websites use cookies to log their users in automatically. By storing a few pieces of user
information they can automatically authenticate the user's details and use them to save the user
time when they log in>/li>

 Visitor tracking and statistics systems often use them to track visitors. By assigning the visitor a
cookie, they will not be counted more than once, so accurate unique visitor statistics can be
obtained. Also, if a user has a unique cookie the system can 'follow' them through a website,
showing the webmaster exactly where the visitor has been, and in what order.

Using Cookies
A cookie is a very basic data file. It has a name and a value and also stores the address of websites
which are allowed to access it and an expiry time. Basically, a website will set a cookie and give it a name
and value. This name is used by the website to refer to it, and no other website can access the cookie,
even if they know it's name. The name should be unique to the website, but it doesn't matter if it clashes
with the name of a cookie from another website.

The cookie (as mentioned before) can only store up to 4000 characters of data. This is enough to store
lots of information about a user so if, for example, you wanted to store the user preferences for a search
engine (much like Google does), you could simply list the preferences in the cookie. If you wanted to store
more data, you would have to store a unique ID in the cookie, which matched up with a database record,
and you could th
en access the user's data this way.

To retrieve data, the website simply has to request if the user has a cookie with a particular name. If the
user does, the value is returned to the script and it can be dealt with however the website owner chooses
(for example a name stored in a cookie could be returned, a user ID could be loaded from a database, or
a record could be made of a user visiting a site).

Every cookie is assigned an expiry date and time. It is up to the website owner to decide how long the
cookie should exist for. Many owners may just choose to set the cookie for an hour, meaning it is only
available for the user's single session. This is common in visitor tracking. Other cookies could be set for
much longer. Maybe a week or a month (often used for affiliate program tracking) or even several years
(often used for user preferences).

Cookie Security

Despite much worrying in the news a few years ago, cookies pose no real danger to users. Unless they
are really worried about themselves being recognised by a website, they are harmless. The browser
actually writes and reads cookies from the computer when requested to by a website, so a malicious
website cannot damage the computer.

For webmasters, there are some security concerns. When the cookie is set, the domain(s) which can
access it are set. Usually this is just the website who set the cookie. This makes them relatively secure,
as you can be sure that your competitor cannot load your cookie from one of your visitors' computers
(they cannot even find out if it exisits).

One major security problem with cookies, though, is that they can easily be read by anyone using the
computer. They are just a simple text file, so you should not under any circumstances store passwords in
cookies. A common way to log people in automatically is to store an encrypted version of their password,
which can then be matched with an encrypted version on the server. Another method is to store a unique
ID and a unique validation number on the user's system. This is then referenced in a database to the
user's account. This way, no actual details are stored and a malicious user cannot simply guess users'
IDs (as there is the validation number).

This Tutorial

This introduction has covered some of the basics of cookies and how they are used. The next three
sections cover the setting and reading of cookies using four of the most common scripting languages
available. Each page is a self contained description of how to set and read cookies for that language, so
you should now jump ahead to the section for your chosen language.

Cookies Tutorial
Part 2 - PHP and Cookies
 Part 1 - Introduction to Cookies
 Part 2 - PHP and Cookies

Introduction
This section of the tutorial covers the use of the PHP scripting language to set and read cookies. Cookies
in PHP are not difficult to implement, and there are only two commands that need to be used with them.
PHP makes it easy to set and read cookies and provides all the features needed to give their details.

Setting a Basic Cookie


The PHP function for setting cookies is called:

setcookie()

It is a PHP function which can be used without returning a value (for example you can simply execute a
setcookie()) command, or you can take the return value and use it. The setcookie() function returns a
boolean (true or false) value depending on whether it is successful. So you could execute:

if(setcookie())
{
echo "Cookie set";
}
else
{
echo "Cookie not set";
}

For the purposes of this tutorial, though, we will not be using the return value, instead simply setting the
cookie.

The most basic information for a cookie is it's name and it's value. The name of the cookie must be
something which you can refer to it later as. You don't need to worry about it clashing with other sites as
cookie names are site specific but you should try and use a descriptive and unique name for your
cookies.

For this first example, assume that you have used PHP to load the user's name into the variable $name
and want to greet the user in the future by their name. You would need to create a cookie which stores
their name as follows:

setcookie("UsersName",$name);

This creates the most basic of cookies, storing the user's name in a cookie called 'UsersName'. By setting
cookies like this, you don't set any specific options, so by default the cookie will be available to the
domain in which it was set (e.g. yoursite.com) and will be deleted when the user closes their browser.
Reading Cookie Values
PHP makes it extremely simple to read the value of a cookie. In PHP, reading form values are achieved
using $_GET and $_POST. PHP has a similar global variable for cookies:

$_COOKIE['CookieName'];

This variable contains the value of the cookie with name 'CookieName'. So on your website, if you wanted
to display the name of the user, you could simply use the following:

echo "Hello, ".$_COOKIE['UsersName']."! Welcome back!";

Of course, the user may not already have the cookie, so you should use the PHP function isset. This
returns true if a variable has been set and false if not. Using this, your site could do the following:

if(isset($_COOKIE['UsersName'])
{
echo "Hello, ".$_COOKIE['UsersName']."! Welcome back!";
}
else
{
setcookie("UsersName",$name);
}

Cookie Settings
Although the code I have given you allows you to set a simple cookie on the user's computer, it isn't very
powerful because, for example, it is lost when the browser closes. One of the most powerful features of
cookies is the ability to set and expiry date for the cookie. The cookie will remain on the users computer
until the expiry date, then will automatically delete itself.

To set a cookie with an expiry date, use:

setcookie("UsersName", $name, time()+3600);

This code takes the current time (using time()) and then adds 3600 seconds to it, and uses this value to
set as the expiry time for the cookie. Basically this means that the cookie will remain on the user's
computer for an hour (it expires 3600 seconds (1 hour) from the current time). For one week (for example)
you would set the cookie as:

setcookie("UsersName", $name, time()+604800);

There are three other options which can be used when setting cookies. Firstly the path. This refers to
where in the domain you are able to access the cookie in future. By default this is the cu
rrent directory (so if you set the cookie at the page: www.mysite.com/scripts/setcookie.php, it would only
be available to scripts in the scripts directory and below). You can set this to any part of your site, though,
which can be useful in some situations.

A second setting you can change is the domain. By default, a cookie is only available in the domain you
set it in, for example if you set the cookie on www.mysite.com you can only ever access it from
www.mysite.com (and not mail.mysite.com etc.). The most common need to change this setting is to
allow the cookie to be viewed across all subdomains of a site. This can be done by setting the domain
to .yoursite.com (with both .s). By doing this anything.yoursite.com is accepted, not just
www.yoursite.com.
Finally, a cookie has the option to be set as a secure cookie. If this is turned on, the cookie will only ever
be surrendered to the site over a secure connection, not an insecure one.

The following code shows the imiplementation of a cookie with all settings specified:

setcookie("UsersName", $name, time()+3600, "/", ".mysite.com", 1);

The cookie set here, is called 'UsersName' and again stores the value $name. It will expire an hour from
the current time. It is available in all directories of the site (/ is the root directory). It is available across any
subdomain of the site mysite.com as '.mysite.com' has been given as the domain. The final 1 means that
this is a secure cookie, and can only be transmitted over a secure connection. This would be 0 for a
standard (non-secure) cookie.

Deleting Cookies
There are occasions on which you may wish to delete a cookie from a user's computer. This could be if,
for example, you want to log the user out of a system (perhaps they are on a public computer). Deleting a
cookie is quite simple to do because all you have to do is to set the expiry time in the past. By doing this,
the cookie will be automatically deleted as soon as it is created, and will remove any data that already
exists there. The simplest way is using:

setcookie("UsersName", "", time()-3600);

This sets the expiry time in the past so it should be deleted immediately. There is also no information
stored in the cookie.

There is a known problem with this, though. Although it works in most cases, there can be problems if a
user's timezone is set wrongly. The safest way to completely delete a cookie is to use the following:

setcookie("UsersName", "", mktime(12,0,0,1, 1, 1990));

The mktime() function is a PHP function for setting up a time specified. The time specified here is in the
year 1990, so even a badly configured computer should still delete the cookie immediately.

Conclusion
This short section of the tutorial should cover all the information you will need to set up, manage and
delete cookies in PHP. Using other PHP scripting techniques you can store more data in a cookie (for
example using it to interface with a database). All the information here, though, should allow you to do
practically anything you need to with your cookie. If you want to learn about cookies with other
programming languages, this same information is available in the other parts of the tutorial for them.

ASP Tutorial
Part 1 - Introducing ASP
 Part 1 - Introducing ASP
 Part 2 - Output And Variables

 Part 3 - IF Statements

 Part 4 - Loops and Arrays


Introduction

For any webmaster, once you have created a page with graphics and content, the next logical step is to
make it interactive. You can, of course, go to one of the remotely hosted scripting sites who will provide
you with a simple piece of code to put on your site, but there is a lot more flexibility if you can create and
install your own scripts which will do exactly what you want.

It's thought by many that this 'server-side scripting' (it is processed by the server and not the browser, so
unlike JavaScript the use of ASP doesn't depend on someone's browser supporting it) is very difficult to
learn, and this has come from the early languages like Perl, which are difficult to write and even more
difficult to debug. Over the past few years two new languages have emerged, PHP and ASP. These are
easy enough for even the novice webmaser to learn.

What Is ASP?

ASP stands for Active Server Pages. It is basically a server-side scripting language designed for the
Windows Platform, although it is available on Unix/Linux systems through new systems, although PHP is
the more popular choice for this platform. Active Server Pages is based around VBScript, a variant of
Visual Basic, which makes it very easy to use as the majority of the commands are plain English and
simple to decipher.

As mentioned earlier, ASP is a server-side scripting language. Basically what this means is that if an ASP
page is requested, the web server will process it and run all the ASP code, before sending the output to
the browser. This has two major advantages over client-side (processed by the browser) scripts like
JavaScript. The first is that there are no compatibility problems. It doesn't matter if the user is using the
latest browser or the oldest, they will see the same output. The second is that your code is hidden.
Because code is executed on the server, users only ever see the output, so it is safe to put passwords
etc. in your ASP code.

What Do I Need?

ASP is a server-side language, so you will need to make sure that your web server has the correct
software for running it. The most common setup for running ASP scripts is on a Windows-based server
running IIS (Internet Information Server). It is possible to use Linux-based systems, though, but they must
have the Chillisoft ASP package installed. Most web hosts will publish whether they support ASP, but if in
doubt contact your systems administrator. If you need a free web host supporting ASP, try visiting Free-
Webhosting.info.

Once you have the server ready to accept scripts, running one is as easy as simply uploading and
running the file. You don't need to put it in any particular place on the server or change any settings. Just
upload and run.

ASP Code

When writing ASP you don't need to worry about changing all your HTML, you simply add ASP code into
your HTML pages where needed. YOu also don't need any special software on your computer, a simple
text editor will do. To begin an ASP page you will first need to tell it what language you have written it in.
The most common (and the one used in this tutorial) is VBScript. You should begin your page with:
<%@ Language=VBScript %>

All this code does is tell the ASP system that you are writing your page in VBScript. You will notice that
the ASP code is enclosed in special tags. All ASP code should be enclosed in the 'percent sign tags' in
the form:

<% ASP Code Here %>

Code can be written over multiple lines, but any code not enclosed in the ASP tags will simply be treated
as HTML. Similarly and HTML inside these tags but not specifically sent as output by the code will cause
an error.

Testing ASP

Before you start writing scripts it is a good idea to test whether ASP will run correctly on your server.
Make a simple page with the following:

<html>

n<head><title>Test Page</title></head>
<body>
This is some HTML. Below this I have ASP<br>
<%@ Language=VBScript %><br>
Nothing should appear above here.
</body>
</html>

and save it as test.asp. Then upload this to your server and access it with your browser. If it has worked
correctly, the page should display and you should only see the lines:

This is some HTML. Below this I have ASP

Nothing should appear above here.

If the ASP appears in the page or the source of the page, something has gone wrong. Check the code
and also the settings on your server. No ASP should appear as it should have been processed by the
server before it was sent to the browser.

ASP Tutorial
Part 2 - Output And Variables
 Part 1 - Introducing ASP
 Part 2 - Output And Variables

 Part 3 - IF Statements

 Part 4 - Loops and Arrays


Introduction

In the last part I explained a little about how to write ASP and how to tell the server that you have ASP
code in your file and what language it is written in. In this part I will explain what is probably the most
important use of ASP: output.

Sending Output To The Browser

It's always been a tradition of programming tutorials to begin by writing the simple 'Hello World' program,
so this one won't make an exception! Sending output is done using the ASP command:

Response.Write()

so to write 'Hello World' to the user's browser the complete code would be:

<%@ Language=VBScript %>


<%
Response.Write("Hello World")
%>

Again, this code begins by telling the system that you are writing in VBScript. Then comes the
Response.Write command. Basically this is made up of two parts. 'Response' tells the server that you
want to send information to the user. There are other types of command including: Request (which gets
information from the user), Session (for user session details), Server (for controlling the server) and
Application (for commands relating to the application). More about these later.

The second part, 'Write', tells the server that the type of response you would like to send is to write
information to the user's browser. This doesn't just have to be text, but can include variables, which will be
discussed in more depth later in this tutorial.

Variables

Probably the most important feature of a programming language is a variable. A variable is basically a
way of storing text, numbers or other data, so that it can be referenced later. For example, to change the
earlier 'Hello World' script:

<%@ Language=VBScript %>


<%
OutputText = "Hello World"
Response.Write(OutputText)
%>

The output of this code will be exactly the same as the first script, but it is fundementally different as it
uses variables. Basically what this code does follows:

OutputText = "Hello World"

This line sets up a variable called OutputText and stores in it the string of letters 'Hello World'. As this is
now stored in a variable, you can now reference this text you have stored in any part of your script, and
you can also manipulate it. The next line:

Response.Write(OutputText)

tells the server that you are sending information to the browser, and that the information to be sent is the
contents of the variable called OutputText. Please note that the variable name is not enclosed in
quotation marks. If you did this the browser would simply output the title of the variable as text.

There is a second way of outputting the values of variables, other than using Response.Write. The earlier
code could have been written:

<%@ Language=VBScript %>


<%
OutputText = "Hello World"
=OutputText
%>

In this example, the = sign is used instead of ResponseWrite.

Variable Operations

The main benefits to storing information in variables is that you can use the text over and over again. For
example, once storing "Hello World" in the variable OutputText, I can then use it in various places in my
code:

<%@ Language=VBScript %>


<%
OutputText = "Hello World"
%>

This is my <% =OutputText %> script. The whole reason for it is to output the text <% =OutputText %> to
the browser.

which would display in the browser:

This is my Hello World script. The whole reason for it is to output the text Hello World to the browser.

You can also do various operations on text stored in variables using len, left and right.

The len function simply tells you how many characters are in a string, so if you used the following code:

<% =len(OutputText) %>

The server would return to the browser the


length of the text stored in OutputText, in this case "Hello World", so the browser would display the
number 11 on the screen. You could also assign this value to a variable using:
<% StringLength = len(OutputText) %>

which would set the value of the variable called StringLength to 11.

You can also use the functions left and right. These will display only part of the variable. For example:

<% =left(OutputText, 2) %>

which would display:

He

and the code:

<% =right(OutputText, 4) %>

would display:

orld

Basically, these functions take the number of characters specififed from the left or right of the string, so
left("Some Text", 5) takes the first 5 characters of the text.

You might also like