PHP Lessons 9: Session and Cookies

by
Guest-GS

Hello there, back with some PHP lessons. It’s been quite a while. Got loads of projects to deal with at work and wasn’t feeling like typing codes at home.

This lesson will deal about session ($_SESSION) and cookies ($_COOKIES)…(This kind of cookie has nothing to do with cookies our grand-mother used to cook for us 😀 )

SESSIONS:

What are session and how can they be useful?

Sessions in PHP are meant to keep track and store data for a particular user while they browse our site or pages. For example, with a login system, when the user logs in, PHP must have a way to keep track of the user’s status and with this kind of info, we can allow registered user to access private areas and so on. We can also store other data like what time they logged on, and show messages like: “You’ve been here for X minutes”.

When you start a SESSION, a random Session Id is stored in a COOKIE and the default name is PHPSESSID. Yes, even if it’s a SESSION, the value is also stored in a COOKIE an placed on your computer. The advantage of SESSION is, even if the user has cookies disable on his browser, SESSION will still keep track of user info, because, SESSION not only adds PHPSESSID to a cookie, but all values you assign to a SESSION, are also stored in a file on your server.

How do we start a SESSION?

The answer is simple, you just have to add this line on code on top of your page, before any html or php code whatsoever. It HAS to be at the very top, else you can get error messages.

<?php
    session_start();

    //other stuff below
?>

Author’s note : Sometimes, when declaring session_start(), you might get a fancy notice which will drive you crazy. I will tell you about it later in this chapter.

Let’s try something with SESSION. We will declare a SESSION, assign a value to it, and retrieve the value. Code’s below:

<?php
     session_start(); 

     $_SESSION['view'] = 1; // assign value to session
     echo "Pageviews = ". $_SESSION['view']; //retrieving the value
?>

Let’s analyze this,

1) We declared our session on top of everything.
2) we assigned the value of 1 to the SESSION array at position “view”: $_SESSION[‘view’]. We hence called the SESSION, “view”. Yep, $_SESSION is just an array!
3) We echo out the value of the SESSION.

If you run this code, it will print 1. Cool huh?

With this, we can determine how many times a page has been viewed. The code below:

<?php
    session_start();  //declare session

    if(isset($_SESSION['view']))
       $_SESSION['view'] = $_SESSION['view']  + 1;

    else
       $_SESSION['view'] = 1;

   echo 'You viewed this page '. $_SESSION['view'].' times.';
?>    

This one looks a bit different, we added a condition to check the value of our SESSION.

First, if the session is already set (isset()), We just add 1 to it. According to our condition here, if it’s there, lets just increment it, else we default the value to one.

If you try this code, keeps refreshing your page, and you will see the numbers increasing in value as you refresh.

As you already noticed by now, $_SESSION is also an Array.

<?php
   session_start();

   $_SESSION['firstname']   = 'John'; // Assign value to session called firstname. (Hello again, Mr. John!)
   $_SESSION['lastname']    = 'Dingo';
   $_SESSION['age']         = '18';
   $_SESSION['location']    = 'Mauritius';
   $_SESSION['sex']         = 'Male';

   echo '<pre>';
      print_r($_SESSION);
   echo '</pre>';
?>

Try the code above, it will print an array of the $_SESSION we declare, and yes, it will echo ALL the session we declare, including the view $_SESSION from before. But now, why is it echoing out a $_SESSION that we didn’t declare in the script above? Well, remember, SESSION are being stored on a file on your server. The $_SESSION called “view” is still in there and we are looking at a complete Array of all SESSIONS that has been set.

How do we get rid of this view SESSION then?

In order to achieve this, we have to unset the session view. The name says it all because the built-in function we are going to use is called : unset();

Try the code below:

<?php
   session_start();

   $_SESSION['firstname']  = 'John'; // You again, Mr. John?
   $_SESSION['lastname']   = 'Dingo'; //
   $_SESSION['age']        = '18';
   $_SESSION['location']   = 'Mauritius';
   $_SESSION['sex']        = 'Male';

   unset($_SESSION['view']); //gets rid of the view 

   echo '<pre>';
      print_r($_SESSION);
   echo '</pre>';
?>

Refresh your page and TADA! the $_SESSION called view is gone. Now, since $_SESSION is an array. We can use the foreach() loop as well as the for() loop to deal with Multidimensional Arrays. 😀

Let’s experiment. Code below:

<?php
    session_start();

    $_SESSION['msg'] = array(); //We assign our message session as an empty array;

    $_SESSION['msg']['msg_one'] = 'Hello this is message one.';
    $_SESSION['msg']['msg_two'] = 'Hello this is message two.';
    $_SESSION['msg']['msg_three'] = 'Hello this is message three.';

    echo $_SESSION['msg']; // This will only output Array to our browser. So we don't see any values

    echo '<hr />';

    if(is_array($_SESSION['msg'])){
       foreach($_SESSION['msg'] as $myMsg){
          echo $myMsg.'<br />';
       }        
    }

?>

As you can see here, when we  echo $_SESSION[‘msg’];, it only outputs Array to our browser. We need to access the data in this array. Remember the foreach loop? It comes in handy there, we are iterating over the Array and outputting it’s value. The results will look like this:

Hello this is message one.
Hello this is message two.
Hello this is message three.

You will notice a new little function called is_array(). This is a built-in function that checks if the argument being pass in an array. This function returns true or false, in our case, it will return true since $_SESSION[‘msg’] was set as an array to begin with.

Sometimes, these built-in functions comes in handy especially when you’re dealing with dynamically generated data.

You can start a session, but you can also destroy a session. Yes, you can. How?

Just by adding session_destroy() in your script.

Note that, when you close all your browsers, the session is automatically destroyed or cleared if you prefer. But some browsers like Mozilla Firefox sometimes asks you if you would like to save data before closing, if you choose yes, then I believe all the SESSIONS are preserved.

Earlier, i told about session_start() generating an ugly PHP Notice. This is true. Even if it’s a built-in function. How come? Well, let me explain something. In your PHP Configuration (php.ini file), there a line which says:

session.auto_start = 0 or session.auto_start = 1

What this means is, when ‘session.auto_start = 1’, PHP has the power to start a session for you automatically, without you having to put session_start() at top of your script and if it is 0, then you will have to add session_start() at top of your script. PHP starting a session automatically for me. Cool huh? Not so quick pals, this can cause some serious damage later. Follow on.

Let’s assume the server your using right now, has session.auto_start set to 1. With this, you might say, ok, PHP is doing it for me, so I won’t bother adding session_start() in my script. But, what if you move your site on another server, and this another server PHP configuration has session.auto_start set to 0? That means your scripts won’t work and you will get some ugly error messages and yes YOU will have to go in your scripts and add session_start() everywhere where your scripts are using session.

Now, since we are good programmers, we must find a way to make our scripts cross-server. Bypassing this problem is actually quite easy. When a session is declared, a session_id is being generated. Remember, I told you that at the beginning of the lesson? In PHP, you can check if a session_id exist. We use the session_id() built-in function. With this, we can make a condition to bypass our problem. Code below:

<?php
   if(!session_id()) { session_start(); }

   $_SESSION['msg'] = array(); //We assign our message session as an empty array;

   $_SESSION['msg']['msg_one'] = 'Hello this is message one.';
   $_SESSION['msg']['msg_two'] = 'Hello this is message two.';
   $_SESSION['msg']['msg_three'] = 'Hello this is message three.';

   echo $_SESSION['msg']; // This will only output Array to our browser. So we don't see any values

   echo '<hr />';

   if(is_array($_SESSION['msg'])){
      foreach($_SESSION['msg'] as $myMsg){
         echo $myMsg.'<br />';
?>

Have a look at the very first line in the code above. The condition says, if there’s no session_id, then we use the session_start. This will get rid of the pain ;). I strongly advise that you use this method when starting a session. Believe me, it will save you some time later.

That’s it for $_SESSION. Moving on with $_COOKIES.

Cookies

Unlike the cookies we used to eat, this one is a bit tricky and less tasty, and the syntax is different from SESSION. We don’t start a cookie, we SET a cookie. I believe you all know what browser Cookies are. It’s a way to store data on the users computer in small files.

When a website places a cookie on your PC, it’s to determine wether you have been on this site recently. Usually when you login on a website, there’s a checkbox which says “Remember Me”, if you check it, the script will place a cookie on you computer, after two days, when you go to that same site, the script will check if a cookie exist, if it is, you won’t have to login again, you’re already logged in. Cool huh .. The syntax for COOKIE is below:

setcookie(name, value, expire, path, domain, secure); 

name     = the name of the cookie
value    = the value of the cookie
expire   = the amount of time the cookie will remain alive
path     = which path on your server you want the cookie to be accessible
domain   = the domain that the cookie is available
secure   = Indicates that the cookie should only be transmitted over a secure HTTPS connection from the client.

Below is an example of how to work with cookie:

<?php

    if(isset($_COOKIE['username'])){
       echo "You were there recently ".$_COOKIE['username']." Nice to have you back pal";
    }
    else{
       echo "Hi, you're new here. What is you name?";
       setcookie('username','John',time()+3600,'/');
    }

?>

In the code above, we first make a condition to see if a $_COOKIE name ‘username’ was set. If it was, then it means the user was here recently. Else, it’s his first time, so we show him a message stating that his new, and then, we set a cookie using the setcookie function.

We named our cookie username, we gave it a value of John ( In this example, the value can be anything ), then we set the expire time, in our case, the cookie will expire in 1 hour (in seconds, 1 hour = 3600 seconds). The last parameter is the path; I want this cookie to be accessible everywhere on my server. After expiry, it means the cookie is no longer valid. If the user returned after say, 5 hours, he’ll get the message destined to new users. This is useful when you have checkboxes like “Remember me for a day”. Set the expiry of the cookie to one day, and you’re done.

You will notice that I omitted the domain and secure parameter, it is optional.

If you run the code, you will get: Hi, you’re new here. What is you name?… and a cookie will be set.

But if you refresh it again, you will get: You were here recently John. Nice to have you back pal!, since our condition saw a cookie named “check”.

Remember, John is the value of our cookie, that’s why we get his name in th first if statement.

To get an entire $_COOKIE Array, just run the code below:

<?php

   echo '<pre>';
   print_r($_COOKIE);
   echo '</pre>';

?>

You might get a big Array along with a bunch of values, depending on how many sites has a cookie on your PC 🙂

Now that we know how to set a cookie, but how do I delete the cookie? Interesting question. Unlike SESSION, a cookie cannot be delete using the unset() function, neither exist a built-in function call destroy_cookie(). You can’t go on deleting files on the user’s machine, can you?

To delete a cookie, you simply set the expire time in the past.:

Code below:

<?php

   if(isset($_COOKIE['username'])){
      setcookie('username','john',time()-3600,'/');
      echo 'Cookie has been deleted.';
   }

   echo '<pre>';
      print_r($_COOKIE);
   echo '</pre>';
?>

In our if statement, have a look at the setcookie function and analyze the parameters, something has changed. Notice the time()-3600 . Before we did time()+3600. But we wanted to erase it, so we defined the time 1 hour in the past. This will get rid of the cookie. Have a look at the Array, you will notice that John isn’t there anymore. He’s gone. Poor guy. He’ll be back, don’t worry.

Cool, we know how to set a cookie. But what about that time() function you keep talking about?

Well, PHP allows you to work with time. The function time() doesn’t actually return something like 19:50:23. Instead,it returns the current time as a UNIX TimeStamp (the number of seconds since January 1 1970 00:00:00 GMT). This is used as a reference time point to know much time elapsed. It’s the computer’s way of asking: “How long has it before you have eaten?”. So you figure out when you last ate, check what time it is now, and do a substraction and say, “5 mins ago”.If you echo time(), you will get something similar to this:

1268422287

Yes,a bunch of numbers. What the hell is that? That’s how a computer knows “Now”. 7 seconds ago would be:

1268422280

I want a good formatted time. Ok, to compensate for the delay of the PHP Lessons, I will show you some examples of how you can format a date and time using the number of seconds return by time(). The time() function, doesn’t take any parameters. In order to get a nice format of the date and time. We should use the date() function in addition with the time() function. Example below:

<?php
   echo 'Current time is : '. date('Y-m-d H:i:s',time()); // outputs Current time is : 2010-03-12 23:35:40
?>

This code will give you the current time. Well, depending on your server, you might get a time 4 hours earlier than that. If that’s the case, to get the current time, you will need to offset your date() function. Example below:

<?php
   echo 'Current time is : '. date('Y-m-d H:i:s',time() + 14400);
?>

You already noticed, we added 14400 with the time() function. Why 14400? Little maths below:

1 minutes           = 60 seconds, So
1 hour              = 60 minutes, So to get the numbers of seconds in 1 hour, we do
1 hour in seconds   = 60 seconds * 60 minutes which = 3600

Now we know 3600 seconds equals 1 hour. 
To get an offset of 4 hours, we multiply 3600 by 4. The result is 14400.

Next we add it to our time() function. Isn’t PHP great?

To get a list of available format of date and time, I strongly suggest you visit this link : http://php.net/manual/en/function.date.php.

While i’m at my little ‘compensating for the delay of lesson’, let’s go back in the past where we used to talk about user defined function.

This is a bonus for you.

When we create our own function, we can pass in arguments, as many as we want. What if one day, our function requires unlimited number of arguments? Supposed some numbers are being returned from a database, we want to make some maths or whatever with those numbers, and it so happens we are getting about 1000 rows of numbers. Are we going to write a function that takes 1000 arguments? If you have the time to type all that, then good luck. But instead of typing, let me show you how to create a function of your own, that can take unlimited amounts of args.

<?php
   function unlimitedArgs(){
 
      $arguments = func_get_args(); // returns an array of arguments passed to the function when calling it
 
      foreach($arguments as $args){
         return array_sum($args);
      }
   }
 
   $someArray = array(1,2,3,4,5);

   echo unlimitedArgs($someArray);

?>

Let’s analyze, first, for a beginner, things looks weird, because we are creating a function that doesn’t take any arguments, and yet, when we call that function, we are passing an array as it’s arguments. Have a look at the function, we have this line:

$arguments = func_get_args();

func_get_args() returns an array of any arguments passed to the function even if we didn’t supply it when created the function itself. This way, we can pass as many arguments as we want. In our example, our argument is an array containing numbers. Our function simply iterates over the array of arguments created by func_get_args, then we use the array_sum function to sum up all the values in the array. Our result is 15.

array_sum(Array) simply sum all the values in the given array.

Ok, I believe this is it for this lesson. If you didn’t understand the last part, comments are open for questions! 🙂

Nice reading.

This article was contributed by Tipa of Mu-Anime

[seriesposts title=”PHP Lessons” titletag=h3 listtype=ul orderby=date name=”PHP Lessons” ]

  • ramesh

    Thanks for the update.
    Keep it up 🙂 🙂

  • The tutorial are getting bigger and bigger as the time goes by. lol 😀

  • ayush

    i get some idea about session when i read it first time
    thanks for posting this lesson

  • kyu

    Ha 🙂 Thanks. we quickly skimmed over php @ uni but this is really helpful (especially the func_get_args() thingy in fact)

    heh, on a sidenote, i am wondering what could be the future of cookies and server side sessions with the introduction of local storage and session storage in html 5 ^^