When to use $_SESSION vs $_COOKIE

A critical feature in web programming is the ability to seamlessly pass data from one page load to the next. It’s used most commonly when dealing with user logins, but also for passing error messages, shopping carts, etc.
Storing data across pages using PHP is done with two variables in the global scope, called $_SESSION and $_COOKIE, and although accomplishing the same end goal, the both go about it in very different ways. The purpose of this article is to give a brief look into the differences between cookies and sessions, when it’s better to use one versus the other, and the pros and cons of the two.
The difference is in how each store data. Cookies store data locally in the user’s browser, while sessions store data on the webserver.
Session Basics
Sessions are simply server-side cookies each with a corresponding client side cookie that contains only a reference to its server-side counterpart. When a user visits a page, the client sends the reference code to the server, and PHP will then match that reference code to a server-side cookie and load the data in the server’s cookie into the $_SESSION superglobal.
Pros
- Can store very large amounts of data easily.
- Save bandwidth by passing only a reference to the session each pageload. A client-side cookie has to pass all of its data.
- Data is stored on the web server. This makes sessions secure, because the data cannot be viewed or edited by the client.
Cons
- Ends when the browser is closed unless you’ve configured php.ini to extend sessions’ cookie lifetime. Cannot last forever.
Cookie Basics
Cookie data is sent to the web server every page load. PHP reads and stores the value into the $_COOKIE superglobal. When a cookie is created, you can give it a lifespan. After that lifespan runs out, it will expire.
Pros
- Can last as long as the website needs. They will still be there even if the browser is closed and reopened.
- Useful for “remember me” logins
- Useful for storing temporary user settings. For example, if a user is browsing a paginated list of items, sorted a certain way, the sorting setting can be stored in a cookie.
Cons
- Stored in the users filesystem. This means that the user can tamper with it and view it.
- Can only store a limited amount of data.
- Must pass all data to the webserver each pageload. This takes up more bandwidth.
Cookies in Action
Creating a cookie
The function definition:
bool setcookie ( string name [, string value [, int expire [, string path [, string domain [, int secure]]]]])
<?php
if (!isset($_COOKIE['Ordering'])) {
setcookie("Ordering", $_POST['ChangeOrdering'], time() + 31536000);
}
?>Using a cookie
<?php echo (isset($_COOKIE[‘ordering’])) ? $_COOKIE[‘ordering’] : ‘cookie value not set’; ?>
Deleting a cookie
<?php setcookie(‘favorite_color’); ?>
Setting a cookie with no value is the same as deleting it. This will not remove the file from the client computer. To do this, you can set the cookie expiration date to a time in the past, and the browser will take care of it.
Sessions in Action
Creating a session
<?php session_start(); ?>
This must be called near the top of your code before any output. When you call this function, PHP will check to see if the user sent a session cookie. If so, it will load the session data into $_SESSION. If not, it will create a new session file on the server and send the ID back to the client.
Setting a value
<?php $_SESSION[‘first_name’] = ‘Brian’; ?>
Reading a session value
<?php echo $_SESSION[‘first_name’]; ?>
Removing session data
<?php unset($_SESSION[‘first_name’]); ?>
Ending a session
<?php session_destroy(); ?>
The Bottom Line
Sessions are cookies where the data is stored on the server. Cookies are stored in the users filesystem (typically in their “Temporary Internet Files” folder). Both have their advantages, but on any given day, you’ll probably find yourself using sessions much more commonly.














Discussion
July 20th, 2010 at 4:37 PM
Very good and informative article! I have always thought using sessions was much more complicated than it really is! Thanks.
July 20th, 2010 at 5:11 PM
Great post! I find that some people blur the lines between them and just end up using whatever comes to their mind first. It’s important to be decisive when programming, and this is a great example of that.
July 20th, 2010 at 9:20 PM
I discussed this topic with a friend of mine recently.
When you encrypt the cookies values there is no difference.
So in the end the only difference is “amount of traffic and limited stored data” vs “limited lifetime”
When you have heigh amounts of data to be stored you should use a real database anyway and not just the php’s (or other serverside language) own session store.
But there is not stored much data in session in most cases leading to the cookie being the best choice in most cases because of the unlimited life time.
I am not sure if the argumentation is valid but my friend convinced me after I was using session for years.
July 20th, 2010 at 11:23 PM
“Data is stored on the web server. This makes sessions secure, because the data cannot be viewed or edited by the client.”
I think this is a little misleading, PHP Sessions are not secure unless you add an extra layer of security in your code like in this article:
http://thinkvitamin.com/dev/how-to-create-bulletproof-sessions/
Also you need to store your session data in a database table not rely on php’s native sessions.
July 20th, 2010 at 11:47 PM
@Laszlo and Jon
Obviously, this article oversimplifies the usages of sessions and cookies for the sake of clarity. The purpose is to define on a very fundamental level what they are, the differences and advantages of either, and present some very basic usages of both.
Someone who knows the ins and the outs of session management already, like yourselves, won’t find this article as useful.
July 21st, 2010 at 3:34 AM
Al tough this article simplifies sessions and cookies it should be noted that sessions are not the same as “serverside cookies” and a more in-depth explanation is in order. The risk here is that beginning programmers will use sessions or cookies in the wrong way. Like storing a user ID or even a password in a cookie or session.
July 21st, 2010 at 4:05 AM
I think most web apps store a cookie which instantiates a session upon returning to the website ^_^.
July 21st, 2010 at 7:00 AM
Nice article.
But please note that sessions also set cookies (or add a query string like PHPSESSIONID=xxxxxxxx). This means that you can make a session last longer than till closing the browser (like stated at session cons.)
So lifetime and (as Laszlo and Jon already stated) security ain’t the issues. The only big difference is the amount of data which can be stored.
A new technique in HTML5 can do the same: HTML5 SQL. This basically creates a local database at the clients computer/phone/etc which makes it possible to use applications without internet access (and synchronizes when your online again). This method can also be used to store temporary data, without any requests.
July 21st, 2010 at 8:01 AM
Just a little tip, on cookie to send the expire time, use strtotime[1], because is more easy send a value this way like:
setcookie(“Ordering”, $_POST['ChangeOrdering'], strtotime(‘+1 year’));
I tell the cookie to expire on 1 year.
Sorry about the poor english, but I wished send the message. I hope somebody understand the concept.
[1] – http://php.net/manual/en/function.strtotime.php
July 21st, 2010 at 8:13 AM
Nice article!
Although it seems unfinished. That, or the title is completely misleading, as the article says nothing about when to actually use on or the other.
July 22nd, 2010 at 7:07 AM
Nice explanation..
July 28th, 2010 at 12:45 AM
nice article…
what about session stored into databases ? when are they used ?
July 28th, 2010 at 8:59 AM
Great article – I always have clients asking me about the security implications etc of storing files on host machines – maybe i will use this to help them understand cookies a little more.
Seon
July 31st, 2010 at 7:21 PM
nice post good work I visit your site daily
and work on it daily Hacking & Blogging
August 3rd, 2010 at 6:04 PM
thanks for post very nice
August 7th, 2010 at 1:03 PM
Nice article!,Thansk.
August 13th, 2010 at 8:47 AM
Great article, thankyou!
August 14th, 2010 at 11:37 AM
This is really helpful, thanks for article, great stuff!
August 31st, 2010 at 9:32 AM
Well this is so good thanks a lot for posting mate .
Join the Conversation!
Remember: Life's not all doom and gloom, so please keep it constructive. If we've made an error or missed something big, please let us know! Learning is revisions, after all.