Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should I use session variables instead of cookies?

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?

like image 1000
sprugman Avatar asked Feb 10 '10 21:02

sprugman


People also ask

Should I use session or cookies?

Session is safer for storing user data because it can not be modified by the end-user and can only be set on the server-side. Cookies on the other hand can be hijacked because they are just stored on the browser.

Why are sessions better than cookies?

Cookies are used to store information in a text file. The data is saved in an encrypted format during sessions. Cookies are stored on a limited amount of data. A session can store an unlimited amount of data.

What is the difference between a session variable versus a cookie?

Cookies are client-side files on a local computer that hold user information. Sessions are server-side files that contain user data. Cookies end on the lifetime set by the user. When the user quits the browser or logs out of the programmed, the session is over.

For what purpose session variables are used?

Session variables are special variables that exist only while the user's session with your application is active. Session variables are specific to each visitor to your site. They are used to store user-specific information that needs to be accessed by multiple pages in a web application.


1 Answers

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

like image 116
Daniel Vassallo Avatar answered Sep 22 '22 23:09

Daniel Vassallo