When to use $_SESSION vs $_COOKIE

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

  1. Can store very large amounts of data easily.
  2. Save bandwidth by passing only a reference to the session each pageload. A client-side cookie has to pass all of its data.
  3. Data is stored on the web server. This makes sessions secure, because the data cannot be viewed or edited by the client.

Cons

  1. 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

  1. Can last as long as the website needs. They will still be there even if the browser is closed and reopened.
  2. Useful for “remember me” logins
  3. 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

  1. Stored in the users filesystem. This means that the user can tamper with it and view it.
  2. Can only store a limited amount of data.
  3. 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]]]]])

Using a cookie

Deleting a cookie

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

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

Reading a session value

Removing session data

Ending a session

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.

PHP Documentation

  1. PHP Manual: Sessions
  2. PHP Manual: Cookies

Posted Tuesday, July 20th, 2010 · Back to Top

SPONSOR

Add Comment

68 Comments 8 Mentions

  1. Montana Flynn Author Editor

    Very good and informative article! I have always thought using sessions was much more complicated than it really is! Thanks.

    ·

  2. Max Luzuriaga Author Editor

    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.

    ·

  3. Laszlo Korte Author Editor

    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.

    ·

    • Brian Author Editor

      “When you encrypt the cookies values there is no difference.”

      Correct me if I’m wrong, but the client can clear / dump cookies, correct? If this is so, I believe your statement is invalid. Sessions are great because the client cannot dump them, however I believe this comes down to exactly what you’re building. If you’re denying a user access over a certain period lets say, I’m trying to think how using cookies would be better than a session, if the user could just dump their temporary files and re-visit…

      ·

  4. Jon Author Editor

    “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.

    ·

  5. Brian Muse Author Editor

    @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.

    ·

    • Malaysian Author Editor

      Hi, your post were detailed enough for us to learned.

      I had try to disable the web browser cookie and both $_cookie and $_session can not function.

      This meant both needed to enabled cookie to be function?

      I known that $_cookie’s cookies stored at client computer, but the $_session reference code that sent from the web server were stored at where? At the client browser too? One reference code at the web server and the other one at web browser? If so,then it will be temporarily?

      I hope you can help me, thanks for your times

      ·

  6. Jorgen Author Editor

    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.

    ·

  7. helium Author Editor

    I think most web apps store a cookie which instantiates a session upon returning to the website ^_^.

    ·

  8. Johan de Jong Author Editor

    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.

    ·

  9. Mauro George Author Editor

    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

    ·

  10. Ted Johansson Author Editor

    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.

    ·

  11. Srinivas Tamada Author Editor

    Nice explanation..

    ·

  12. Harsha M V Author Editor

    nice article…

    what about session stored into databases ? when are they used ?

    ·

  13. Seon Poppcile | web designer Author Editor

    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

    ·

    • Website Traffic Author Editor

      Thank you for the great article I did enjoyed reading it, I will be sure to bookmark your blog and definitely will come back from again. I want to encourage that you continue your great job, have a good day.

      ·

  14. buzukh Author Editor

    nice post good work I visit your site daily
    and work on it daily Hacking & Blogging

    ·

  15. esranull Author Editor

    thanks for post very nice

    ·

  16. MyBB Author Editor

    Nice article!,Thansk.

    ·

  17. Chris Author Editor

    Great article, thankyou!

    ·

  18. Design Vibe Author Editor

    This is really helpful, thanks for article, great stuff!

    ·

  19. Philwebservices Author Editor

    Well this is so good thanks a lot for posting mate .

    ·

  20. Ward O. Author Editor

    What´s happened to buildinternet.com? There haven’t been any new articles for over a month, such a shame, used to visit this website a lot.

    ·

  21. nashekrashe Author Editor

    looking forward to read more…

    Sam? Zach?

    ·

  22. Chris Author Editor

    I’ll second (um, third?) the last two comments…I’ve really enjoyed this website and have learned quite a bit. Hope everything’s okay with the brothers Dunn!

    ·

  23. Boba Author Editor

    If you gave up on BuildInternet just let us know that everything is ok with you.

    ·

    • Zach Dunn Author Editor

      Hi Boba. I actually just got a similar email and I thought I’d post the response here for everyone.

      “Our lack of posting on Build Internet is an unfortunate side affect of a boom in client work. In the past several months, our company has grown to include 3 employees (plus Sam and I) with a number of big ticket brands. Sam and I have every intention of launching the 95% completed as soon as we get our stuff in order. Especially after what we’ve been up to, we have a ton of great articles we’d like to write.

      Build Internet is our child. I don’t ever want to see it go away. We think that the work we’ve been doing on the client end will actually end up helping the blogs in the long run. More projects = more employees = more spare time for Sam & I = More BI.”

      Short version? We’ve got some stuff in the pipeline, and we’ll get it out ASAP. You guys are wonderful.

      ·

  24. Ward O. Author Editor

    Great :)

    ·

  25. Boba Author Editor

    @Zach – Yeah, that email was from me :) I don’t use the full name when i write comments, “Boba” is my nickname.

    ·

  26. James Author Editor

    Nice article. I had read a lot of articles before but cant clear my doubts between session and cookie. But now after this article i am very clear of the advantages and disadvantages of both. Thank you very much.

    ·

  27. shashank chinchli Author Editor

    cookies can be stolen,modified or lost that made me switch to session :)
    thanks for this post dude!

    ·

  28. BoiteaWeb Author Editor

    Nice post, good explaination.
    Just regret that the security side have not been involved !
    Thanks

    ·

  29. tütüne son Author Editor

    Thank you, very nice.

    ·

  30. Sagar Ranpise Author Editor

    Very clear and informative post. Thanks for sharing!

    ·

  31. bohemianGrunge Author Editor

    Great article.
    We can also use the PHPSESSID to use session variables without depending upon any browser based cookies. All we need to do is pass this variable with every URL.

    ·

  32. Kenji Author Editor

    Wow, thank you very much. This helped me a lot.
    Good explanation.

    ·

  33. Ahmed Author Editor

    I was searching for a proper explanation of $_SESSION , luckily got here … seriously it was super helpful n crystal clear explanation .
    Thanks .

    ·

  34. Mongo Author Editor

    this post helps me a lot .”session is server side cookie”

    ·

  35. Kiss Honlapkészítés Author Editor

    Excellent post!
    Thank you, you have been most helpful.

    ·

  36. tütüne son Author Editor

    Good website.i love this post.Thank you

    ·

  37. atlanta remodelling Author Editor

    Excellent tips. Really useful stuff .Never had an idea about this, will look for more of such informative posts from your side.. good job…Keep it up..

    ·

  38. atlanta remodeler Author Editor

    I am very enjoyed for this side. Its a nice topic. It help me very much to solve some problems. Its opportunity are so fantastic and working style so speedy. I think it may be help all of you. Thanks

    ·

  39. atlanta home remodeling Author Editor

    I was just looking for this info for a while. After six hours of continuous Googleing, at last I got it in your site. I wonder what is the Google’s issue that does not rank this type of informative sites closer to the top. Generally the top sites are full of garbage.

    ·

  40. atlanta general contractor Author Editor

    Took a lot of time to read but I really found this very interesting and informative, thank you buddy for sharing.

    ·

  41. outdoor swing set Author Editor

    “Thanks a lot for discussing this matter. I concur with your conclusions.The point that the data stated are all first hand on actual experiences even help more…

    ·

  42. outdoor swing sets Author Editor

    “It is a very informative and useful post thanks it is good material to read this post increases my knowledge..

    ·

  43. play sets Author Editor

    “Thank you so much for this! I have not been this moved by a blog post for a long period of time! You’ve got it, whatever that means in blogging.

    ·

  44. outdoor playsets Author Editor

    “It’s always my pleasure to read this type of stuff.I am very much interested in these types of topics from childhood and it’s my habit to read this.

    ·

  45. Dubai Discount Deals Author Editor

    I know it’s not enough for the meaningful context in your writing as one could understand it easily. Thanks for sharing.

    ·

  46. best deals in dubai Author Editor

    Very good information, nice to find something of use to me keep up the good work, would be nice to see more from you.

    ·

  47. best deals dubai Author Editor

    Appreciate your formulating an exceptionally decent article, It happened to see your website page as well as several written piece. Is exceedingly good type publishing.

    ·

  48. dubai deals Author Editor

    Well done to all who make this film. I want to say huge thank you to this family who take care Lenas kids. Its very important.

    ·

  49. ichigoni Author Editor

    Great article.
    To enable the session last forever we could able to redefine the session storing method, kept session info into database.

    ·

  50. Max Rose-Collins Author Editor

    A nice and simple beginners article.

    Very easy to understand and follow :)

    Bit basic for me but useful none the less.

    P.S. delete the spam comments ;)

    ·

  51. Ping Author Editor

    Life without a friend is death without a witness.

    ·

  52. Train horns Author Editor

    If I ever get married, I’ll check it out!

    ·

  53. Apartments Dubai Author Editor

    I found your blog when I was looking for a different sort of information but I was very happy and glad to read through your blog. The information available here is great.Thanks for sharing…..

    ·

  54. testosterone replacement therapy Author Editor

    I really appreciate the info you showed there. Keep doing what you’re doing. Resources like the one you mentioned here is very useful.

    ·

  55. Today Author Editor

    Today is the first day of the of my life !!!

    ·

  56. Marta Author Editor

    Cookies policy is very important in the way your website works. Thanks all for your input

    ·

  57. http://www.hospiceadvantage.net Author Editor

    tips are provided here.thank you so much.Keep up the good works

    ·

  58. http://www.deweybeachhotels.info/ Author Editor

    Keep up the good works I realize it’s not a popular setup, but it’s still something to keep an eye on. Just shooting you a heads up.

    ·

  59. http://www.hotelchainsuk.org.uk/ Author Editor

    but it’s still something to keep an eye on. Just shooting you a heads up.it’s not a popular setup

    ·

  60. marketing ideas Author Editor

    it’s still something to keep an eye on. Just shooting you a heads up.it’s not a popular setup

    ·

  61. Suzi Smith Author Editor

    Very nice tutorial

    ·

  62. Celebrity Leather jacket Author Editor

    Have a very great day. This is a great way to get comments approved and solicit interaction.

    ·

  63. esta formular Author Editor

    Good tutorial for begginer programmer

    ·

  64. خرید شارژ ایرانسل Author Editor

    nice step by step tutorial

    ·

 

Build Internet by One Mighty Roar. Since 2008.