Subhash AKA “CodeKadiya” is a Software Engineer who is specializing in Web technologies. He has over 7 years of experience in PHP both in industry and freelance work providing web-based solutions for a wide range of clients from many parts of the world. His expertise in programming spans into XHTML/CSS, Apache, MySQL, Javascript/jQuery and AJAX technologies as well. During the past couple of years he has been developing web applications using popular industrial PHP frameworks such as Symfony, CodeIgniter and Zend. He is a FOSS enthusiast and currently employed at Latitude655. Subhash developed a passion for programming at the age of 13 and his swift efficient coding was appreciated by the community of Codewalkers.com. Subhash obtained his Bachelors degree from British Computer Society (BCS). He is currently engaged in a Masters in IT at University of Colombo. He draws extreme pleasure out of listening to music at all times including when he is programming.
 

PHP-Sessions & Cookies

01/02/2010 4:56 am By Subhash Vithanapathirana | Articles: 9

Hi, to all the readers from wherever you are! Our next focus is going to be on handling Sessions and Cookies in PHP. I will be giving you a basic introduction of both before describing the associated source codes.

Sessions

So what are these Sessions? You can think of a Session as a PHP variable which can be used to store information related in some way to the current user of your web application. What makes a Session special compared to a standard variable (which we've discussed in previous articles) is that once a Session variable is instantiated, it is available for access in all the pages of your application. As I state this, some of you might realize how important this kind of functionality would be for your website.

Take a few minutes to think about a situation you might get use of this...

Assume you have a user sign-in form in your website. Once the user inputs the login credentials, you need to validate them against a database in order to know whether he/she is a authorized user of the system (we will learn database connections later). If the user is found to be an authorized one, what would you do? This is where a Session variable come handy. You might want to store the user id of that particular user in a Session variable so that your system can identify he/she is an authenticated user throughout the browsing session. This can help you to provide this user with features which are only accessible by the signed-in users. In other words, Session is the backbone technology of sign-in functionality.

Another situation Sessions are useful is if you're developing an Online shopping cart. Each time the customer presses the “Add to Cart” button, the most convenient method is to store the products information (eg: product id, selling price, quantity purchased etc.) in a Session. Once the payment transaction is completed, you can insert the contents in Session variable to your database for order tracking purposes. If user requests to remove a product from cart, it is just a matter of erasing the Session variable – it makes programmer's life easy!

Sessions are cleared/removed as soon as the user closes the browser window. This makes sure a new browsing session needs to be instantiated when user logs in to the application sometime later. Other than that, pro grammatically you can remove the Sessions simply by unsetting the variable. This method is used when user clicks “Logout” links in websites.

The first step to store information in a Session is to start the session (commonly done on top of the source code) by calling following function:


Once you have the above line of code written in your page, you will have access to all the currently available Session variables. In the example below, I instantiate a Session variable and storing the time which user first accesses the page:


If you remember the previous articles, how we used $_POST and $_GET methods, this is somewhat similar since $_SESSION is another super global associative array available in PHP. Now you are able to access the value of this Session variable in any page of your application, give than you call session_start() at the beginning. I have the following code in a separate page:

Perform several refreshes to the browser and note that the login time does not change as it is saved in the Session by the previous page. If you close the browser and redo the above steps, you'll see that it shows a different time. You can either read or overwrite Session variables as per your requirement. To remove the Session:

Cookies

A cookie is a small file which is stored by the server in user's computer. The information stored in this file can be used to identify the user uniquely across multiple browsing sessions. Unlike Sessions, Cookies does not get cleared upon closing the browser. A cookie can be instructed to hold data for a given period of time.

Have you ever wondered how some websites allow the “Remember Me” functionality in sign-in forms? To achieve this, obviously some data associated with user's computer should be identified by the server – it's called a Cookie!

You should use the setcookie() PHP function to instantiate a new Cookie. We should focus on the first three important parameters of this function.

1. name – the cookie should have a name in order to read them 2. value – the value/data to be stored in the cookie 3. expiration - The date when the cookie will expire and be deleted. If you do not set this expiration date, then it will be treated as a session cookie and be removed when the browser is restarted.

In the above example code, we set a new Cookie called “username” with the value “Rasmus”. Note that this Cookie will be available only within the next 90 days. Once the Cookie is expired, the data stored in it will not be available any longer.

Retrieving the value stored in a Cookie is easy, as another super global associative array exists named $_COOKIE.

Surprisingly, deleting/removing a Cookie is not straight forward as you might've expected (you can't remove a Cookie simply by unset() function). An interesting method is adopted in order to remove a Cookie. Use the same setcookie() function with an expiration date which is prior to the current date:

Once above line is executed, PHP finds that “username” Cookie is something already expired, and needs to be removed immediately from user's computer, so it does just that!

I hope you had an interesting lesson in today's article. If you do have any doubts, either related to Sessions & Cookies or any of the previous articles, you're welcome to forward them to codekadiya at gmail dot com. Wishing all of you a Merry Christmas & a Happy New Year 2010! :-)

Previous Article

 

Share/Save
Your rating: None Average: 1 (3 votes)

Post new comment