For The Beginner - Part 1 : Cookies

Having seen Pablo posts in the Beginner forum, i feel an overwhelming urge to make a tutorial based on his post.

So here goes:

On top of these i will also delve into {If Else} statements and a few other things that i feel are important for a newbie to PHP.

So lets start!

Sessions .VS. Cookies

What are they? Both of these two are methods of storing data for the visitors use (eg, page styles, usernames etc), however the defining difference and the most argued point is:

Cookies are stored on the users computer and can be designated a period of time that the information will exist for.

Eg: The user clicks on a link that changes the background to Green, this link activates a cookies which stores that information into a little file on the users computer. Everytime the user comes back tot he site the background will be green. Now this cookie can be given a time limit, so say the site owner only wants the user to have the background of their choice for 2 hours, the cookie can be set to hold the data for 2 hours then destroy it.

Sessions on the other hand, are server-side, and are usually stored in a /tmp folder under your webviewable folder, and can only hold data for the amount of time that a user has a browser open for. Once all browsers are closed, the session is destroyed.

Now, each of these methods have pro’s and cons.

Sessions Pros & Cons

P : You can store information server-side so you have almost TOTAL control over it.
P : Gives the user MORE security then cookies, as the the data is only available for a single session.
P : There are no worries if the user has disabled cookies.

C : Information can only be stored for the time that the user has a browser open. Once the browsers are closed the information is lost and needs to be re-entered.
C : Because the information is kept Server-Side, it uses system resources and when inexcess of 2000 sessions are running simultaneously RAM and CPU usage can be exhausted.

Cookies Pros & Cons

P : Information can be stored for long periods of time (including infinite)
P : Information is stored Client-Side, so there is no hinderences on System resources.

C : Cookies can be disabled from the clients machines, meaning NO information can be stored for the user.
C : Exploits have been found where cookies can be altered to use on other websites… (nasty)
C : Timed cookies can have issues with the Clients time vs the time on the server.
C : if a cookie is stored indefinately on the users computer without their knowledge, anyone who logs onto that computer and that site will see the original users information.

Conclusion on Sessions .VS. Cookies

Its really a matter of weighing up what you want, or the purpose of using either. For sites that want to have a user logged in for long periods of time, cookies are the way to go. However, cookies can be disable Client-Side, so the site would be rendered ineffective. Sessions on the other hand can’t be forced off by the user as it kept server-side. Sessions are also more secure and cannot be used to exploit other websites.

Personally i use Sessions and find them much easier to use and better for my users.

Using Cookies

Cookies are relatively easy to Setup using PHP. Scenario’s are always good to help.

Say a user has come to my site and i have form that asks what their favourite Cookie is (Chocolate, Almond or Apricot).

The user has chosen Apricot and clicked on the Submit button. Now for each cookie choice a variable has been created out of it. In this scenario the user has chosen Apricot, and for that choice a variable called $Apricot has been created (Fancy that!).

Now to store that information into the database, you would do this:

<?php
    setcookie( "Flavour" , $Apricot );
?>

That cookie is now stored on the users computer, and will be used by the website everytime they go there.

Now setcookie has a few options. if you want to further your cookie and put more information into you can.

Now thats straight out of the PHP.Net manual, but as i have seen not many people know it exists.

Basically what that says is you can further add usefulness and security to your cookie by adding extra string values into it.

Now back to the scenario. Say the web owner only wants the user to have their favourite flavour stored in a cookie for an hour, he can add the expire string into the cookie like so:

<?php
    setcookie( "Flavour" , $Apricot , time() +3600 );
?>

Now the users favourite cookie flavour will only be stored for 3600 seconds, or 1 hour, then the cookie will expire and be rendered useless.

Lets say the website owner wants to go one step further and have the cookie only useful in 1 folder of their site, say http://www.website.com/flavours.

The owner would set the cookie like so:

<?php
    setcookie( "Flavour" , $Apricot , time() +3600 , "/flavour" );
?>

Now the “path” string is being used and the cookie will only reproduce the information stored in it for that folder.

OK, lets take this to the extreme. the website own now has sub-domains on the site:

http://www.website.com
chip.website.com
nocookies.website.com

The owner, now only wants the cookie to work on chip.website.com, by utilising the domain string, thats not a problem.

<?php
    setcookie( "Flavour" , $Apricot , time() +3600 , "/flavour" , "chip.website.com" );
?>

The cookie will now only work at: chip.website.com/flavour

When setting cookies, you MUST enter null values for all the different cookie options eg:

You only want your cookie to last for 10 seconds and in the subdomain chip.website.com, you have to define it like so:

<?php
    setcookie( "Flavour" , $Apricot , time() +3600 , [b]""[/b] , "chip.website.com" );
?>

Checking for an Existing Cookie, and Using its Data

Using the scenario above, i will go through how to use the information stored in a cookie, and how to check if a cookie has actually been set.

OK, now the user has selected apricot as their favourite cookie, and the site owner wants their choice to be printed on the page. But a check to see whether the user has chosen a flavour is needed. This is where the If Else statements will be used in conjunction with cookies.

<?php
    if ( isset( $_COOKIE['Flavour'] ) )
    {
        $Cookie_Value = $_COOKIE['Flavour']; // Get Value from Cookie and assign it to a variable
        echo $Cookie_Value; // Print this variable onto the page
    }
    else
    {
        echo "Html Form with a choice list here"; // Give the Option to choose their flavour
    }
?>

The code is fairly self explanitory, If the cookie exists --> create a varible and add the cookies value to it $Cookie_Value --> Print that value onto the page <-- Else --> Give the user a form to choose which flavour they like the best.

At the risk of making this article to long and boring, i’ve decided to end it here, i hope this has been useful. If you have any questions regarding cookies or would like further explanation on how to use them, just post a reply and i’ll edit the tutorial with what you require.

Seeyas.

Very informative! I use cookies to alter a few things on my site. A new surfer arrives and my code checks for a cookie - if it doesn’t exist the user is asked to complete a simple site survey. If it does then the prompt is not shown. I also use it to make a very subtle change to the index page - very simply it changes the first few words from “Welcome to Kevs Place” to “Welcome back to Kevs Place”.

I didn’t know about making the cookie everlasting (no expiry) until I read your tutorial. I will now alter my code to reflect this as I don’t particularly want it to expire. As it stands I have the code check for the existance of the cookie and, if found, replace it to keep it current. Your way is a lot better.

Thanks for the insights - very well done! :)

Sponsor our Newsletter | Privacy Policy | Terms of Service