60

Session variables and cookies seem very similar to me. I understand the technical differences, but how do you decide when to use one vs. the other?

Daniel Vassallo
  • 312,534
  • 70
  • 486
  • 432
sprugman
  • 17,781
  • 31
  • 105
  • 160

12 Answers12

59
  • Sessions are stored on the server, which means clients do not have access to the information you store about them. Session data, being stored on your server, does not need to be transmitted in full with each page; clients just need to send an ID and the data is loaded from the server.

  • On the other hand, cookies are stored on the client. They can be made durable for a long time and would allow you to work more smoothly when you have a cluster of web servers. However, unlike sessions, data stored in cookies is transmitted in full with each page request.

  • Avoid storing data in cookies

    • It can be seen, read and manipulated by the end user, or intercepted by those with nefarious intent. You can't trust any data in cookies, except for the "session_id".
    • It increases your bandwidth, if you add 1k of data per page request per user, that might increase your bandwidth by 10-15%. This is perhaps not costly from a $$ perspective, but it could be from a performance perspective. It effectively would decrease your bandwidth on a per server by 10-15%, i.e., it might cause you to need more servers.
  • What you can store in session data depends on the amount of data and number of users you have. no_of_users * size_of_session_data must be less than the free memory available on your server.

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Daniel Vassallo
  • 312,534
  • 70
  • 486
  • 432
  • 4
    also to be noted, session data is lost if the web server is restarted – Ben Feb 10 '10 at 21:54
  • 2
    @Ben, not always true, PHP uses files to persist sessions and are therefore resistant to a restart (as is a db store). Generally you only loose session data when they are persisted in memory and or you are using an application server Glassfish etc. – Byron Whitlock Feb 10 '10 at 21:58
  • @Ben: Technically you can have persistent sessions as well. You can have sessions stored in a databased, or on the filesystem, for example. In fact some applications require persistent sessions to keep audit trails of who had access to the application resources. – Daniel Vassallo Feb 10 '10 at 21:58
  • definitely not for all servers, many servers persist session data on disk, in DB, etc. – StasM Feb 10 '10 at 21:58
  • @Ben, ...if session is stored on the web server directly. If you're using a SQL server or state machine to store session (thinking IIS/ASP.NET), it will survive a restart of the web server. – bryanjonker Feb 10 '10 at 21:58
  • @all. Fair points. I must have been working on wonky php servers in the past :) – Ben Feb 10 '10 at 22:03
  • 4
    In fairness, most implementations of "session" will require cookie support so the server can associate client with session. There are cookieless implementations that add extra data to querystrings but generally they are the exception. – spender Feb 10 '10 at 22:09
  • @Byron You can overwrite the PHP session handler to create your own Session handler. On popular method is to store sessions in the DB when dealing with clustered servers – MANCHUCK Feb 11 '10 at 02:22
  • 1
    And you can control how long you should store your session data. Even customize this duration per user. http://php.net/manual/en/function.session-set-save-handler.php – Bimal Poudel Jan 05 '15 at 14:58
  • @ByronWhitlock On Linux the default path to store session variables in is `/tmp`, and by default that is wiped on reboot on many systems. So don't count on PHP sessions persisting over a reboot - it's likely they won't. – Eborbob Aug 06 '15 at 21:03
10
  • Always use sessions
  • Use cookies only if you need longer logged-in sessions - Then add a cookie with an encrypted user ID.
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Bozho
  • 554,002
  • 136
  • 1,025
  • 1,121
8

Most of the time, session state is persisted using cookies. So it's not really a question of one or the other, but how to use them together.

Using your framework's session infrastructure may make things easier, but tracking state manually with cookies usually gives you finer grained control. The correct solution depends on what you're trying to accomplish.

Daniel Pryden
  • 54,536
  • 12
  • 88
  • 131
  • 2
    "The correct solution depends on what you're trying to accomplish." I believe that's exactly what the question's trying to get at.... – sprugman Feb 10 '10 at 23:01
5

Cookies can persist longer than a single session. However, cookies may also be deleted by the user, or you may have a user whose browser does not accept cookies (in which case only a server-side session will work).

danben
  • 73,814
  • 18
  • 117
  • 141
  • This answer is misleading at best. See: https://stackoverflow.com/questions/12572134/php-sessions-with-disabled-cookies-does-it-work – YAHsaves Nov 14 '19 at 06:30
5

Cookies are client-side, and sessions are server-side.

Use cookies for small pieces of data that you can trust the user with (like font settings, site theme, etc.) and for opaque IDs for server-side data (such as session ID). Expect that these data can be lost at any time and they can not be trusted (i.e. need to be sanitized).

Use session data for bigger data chunks (for many systems can store objects, data structures, etc.) and ones you have to trust - like authorization status, etc. In general, use session data for storing larger state data.

You can store things like authorization status in cookies too, if it's needed for GUI, caching, etc. - but never trust it and never rely on it being present. Cookies are easy to delete and easy to fake. Session data is much harder to fake, since your application controls it.

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
StasM
  • 9,840
  • 5
  • 49
  • 96
2

Cookies are sent to the server on every request, so if you plan to store a fair amount of data, store it in a session.

Otherwise, if you are storing small amounts of data, a cookie will be fine.

Any sensitive data should be stored in a session, as cookies are not 100% secure. An advantage of cookies is that you can save memory on your server that would normally be storing session data.

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
JonoW
  • 12,861
  • 3
  • 31
  • 31
2

One of the drawbacks of PHP sessions is how session handling works. Specifically, only one process/request can have a session open for writing at a time. Upon

session_start() 

the session file is locked. If more processes come along, the rest pile up and wait their turn.

In other words, if you are using AJAX on a page to update several elements - you do not want the AJAX requests opening up the same session - they will be forced into a queue and if one of those requests get stuck - it will not release the session - resulting in a browser hang where opening up a new tab or window only puts another unfillable request into the queue on the server. Using

session_write_close()

as soon as possible to release the session is a partial work-around.

A long running request with a user getting bored and opening up more windows could have the same browser hanging effect.

I recommend avoiding PHP sessions.

Dieter Donnert
  • 152
  • 1
  • 8
1

Sessions are stored on the server. If you store something in a cookie, the user's browser sends that information with every request, potentially slowing down your site from the user's perspective. I try to avoid using cookies when I can.

Brandon Montgomery
  • 6,626
  • 3
  • 42
  • 70
  • 5
    But when you're using a session, the server will send a session cookie with every request anyway. I think what you're trying to say is that a minimum of data should be kept in cookies, since all the cookie data will need to be sent across the network on each HTTP request and response. – Daniel Pryden Feb 10 '10 at 21:47
  • Cookies do not "slow down a site" put things into context. a couple of unstructured bytes matter naught. – Hassan Syed Oct 16 '15 at 16:36
0

Use sessions only if the data is too big for cookies or if the data is so big that it would decrease the performance if you used cookies.

For example, if you are saving smaller data then the size of a session ID in your cookie, like two login tokens or something similar... Then I don't see why you would use sessions over cookies.

Also note that PHP session files are saved to disk by default, compared to cookies, which are saved only on the client side.

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Jo Smo
  • 5,847
  • 9
  • 39
  • 64
0

Sessions are stored on the server side. If a visitor stores something in a cookie, the browser will send the user information for every request made.

This tends to consume a lot of servers computer time and slowing the user's experience. Some browsers also do not support cookies giving more advantage to sessions over cookies... I strongly recommend sessions.

This might help: Cookies (php.net)

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
0

Your definite Guide

N.B - A cookie is stored on users' browsers, and a session is stored on your hosting server machine.

When to Use

  1. Use a cookie when you want your application to remember user's data always, even when they have closed their browsers. E.g whenever you type www.facebook.com it takes you to your account, even when your browser has been closed and re-opened.

    Because any data kept in a session is cleared off once you close your browser.

  2. Use a cookie when the user information to be stored is much larger than normal. ... With a session, if you have a larger user base, like Facebook, think of how it will look storing all user sessions on the hosting machine.

  3. Use a session when the user information to be stored is not larger than normal, and you don't want the public to have access to your user variables...

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Emeka Obianom
  • 1,549
  • 3
  • 14
  • 35
0

Sessions and cookies are not the same at all. Cookies are client side. Sessions are server side. Sessions often (but not necessarily) use cookies to correlate one request with another from the same user to identify that they belong to the same session.

A session is an artificial concept, and HTTP doesn't have that notion. It is created by web servers to help web developers carry information across requests, like user account information, shopping carts, form data, etc. A cookie is carried by standard HTTP headers.

The information you store in a session vs. a cookie is up to you. Typically you put stuff in cookies that you want to persist across sessions after the user closes his/her browser. Maybe remembering authentication tokens to implement "remember me" functionality, or past user activity to personalise his/her experience. Keep this information small and "referential", i.e. it could be just IDs that refer to richer information you store sever side. Remember that what is client side is more vulnerable to malware, so don't store passwords or sensitive information.

Finally, there is also local storage, which you did not mention. This is also client side, but arguably a bit less susceptible to cross-site scripting hacks since, unlike cookies data, it is not automatically sent in the headers.

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
jbx
  • 18,832
  • 14
  • 73
  • 129