ChatGPT解决这个技术问题 Extra ChatGPT

Cookies vs. sessions

I started using PHP a couple of months ago. For the sake of creating a login system for my website, I read about cookies and sessions and their differences (cookies are stored in the user's browser and sessions on the server). At that time, I preferred cookies (and who does not like cookies?!) and just said: "who cares? I don't have any good deal with storing it in my server", so, I went ahead and used cookies for my bachelor graduation project. However, after doin' the big part of my app, I heard that for the particular case of storing user's ID, sessions are more appropriate. So I started thinking about what would I say if the jury asks me why have you used cookies instead of sessions? I have just that reason (that I do not need to store internally information about the user). Is that enough as a reason? or it's more than that? Could you please tell me about advantages/disadvantages of using cookies for keeping User's ID?

Thanks for you all in StackOverflow!

Both methods store data. Cookies do so on the client side, i.e. on the storage of your visitors' devices. Sessions are a clever "extension" in that they only store a unique ID on the client side and all the actual data on the server side. When they receive the unique ID from the client's cookie, they know what data to load on the server. In most cases, sessions will be what you need. By the way, you can manage both with github.com/delight-im/PHP-Cookie in a more modern way.
As an aside, WordPress core abandoned the use of sessions several years ago and now uses solely cookies. Interesting. I wonder if they did that to make it easier to deploy across a set of load-balanced servers and/or to reduce random logouts due to session garbage collection.

F
Fosco

The concept is storing persistent data across page loads for a web visitor. Cookies store it directly on the client. Sessions use a cookie as a key of sorts, to associate with the data that is stored on the server side.

It is preferred to use sessions because the actual values are hidden from the client, and you control when the data expires and becomes invalid. If it was all based on cookies, a user (or hacker) could manipulate their cookie data and then play requests to your site.

Edit: I don't think there is any advantage to using cookies, other than simplicity. Look at it this way... Does the user have any reason to know their ID#? Typically I would say no, the user has no need for this information. Giving out information should be limited on a need to know basis. What if the user changes his cookie to have a different ID, how will your application respond? It's a security risk.

Before sessions were all the rage, I basically had my own implementation. I stored a unique cookie value on the client, and stored my persistent data in the database along with that cookie value. Then on page requests I matched up those values and had my persistent data without letting the client control what that was.


@JiminyCricket I don't think that's true... if so, nobody would use session variables for storing the currently logged in user -- and everyone does. It would be a huge security risk. Pretty sure that typically the session ID gets stored AS a cookie on the client machine, and is then matched up server-side with the session data. The server does not typically control sessions via IP address, rather through a cookie value.
I recently just started using only cookies again, purely because sessions make pages not load if there's another one currently being executed from the same session, unless you preface each and every page with session_write_close(); when you need it. Rolling your own unique ID and matching with plain cookies wasn't that difficult, and keeps all the pages nice and snappy.
Do you think I should use sessions for authentication? Does it have any security risks? How about a hacker tries to change his session-id, how would the server respond (suppose the guessed session-id is valid)?
Use session and then 2FA as session can be hijacked.
Of course one needs to sign the cookie set for authorization so you will know if it has been altered and if so reject it. A session has nothing to do with cookies. A cookie is a cookie, a way to store data on the users device. Sessions can be simple or complex, with a database or memory storage, or not. Most frameworks have a session middleware - to authorize users you can set the user id (preferably uuid, etc) and nothing more as long as it is signed. If you are actually doing something with the session other than to just authorize the user on each request you will use a session id and table.
P
Peyman Majidi

Basic ideas to distinguish between those two.

Session:

UID is stored on server (i.e. server-side) Safer (because of 1) Expiration can not be set, session variables will be expired when users close the browser. (nowadays it is stored for 24 minutes as default in php)

Cookies:

UID is stored on web-browser (i.e. client-side) Not very safe, since hackers can reach and get your information (because of 1) Expiration can be set (see setcookies() for more information)

Session is preferred when you need to store short-term information/values, such as variables for calculating, measuring, querying etc.

Cookies is preferred when you need to store long-term information/values, such as user's account (so that even when they shutdown the computer for 2 days, their account will still be logged in). I can't think of many examples for cookies since it isn't adopted in most of the situations.


Be aware: This is NOT a good answer. It starts off quite ok but confuses things and ends with disinformation. This is not a session vs. cookies explanation. It's a session vs. session+session cookie explanation. Cookies alone are not preferred for the reasons stated. Sessions+session cookies are preferred for the reasons stated.
Another mistake is that you do have influence on the session lifetime via PHP configuration.
Sessions still sets a cookie on user browser, so this server-client side explanation is not accurate
sessions expiration can be set by any application easily. 3rd point is wrong. Plus you forgot the amount of data that can be stored in cookie vs session. That's a more significant point
What does IDU stand for?
t
thumbtackthief
SESSIONS ENDS WHEN USER CLOSES THEIR BROWSER,

COOKIES END DEPENDING ON THE LIFETIME YOU SET FOR IT. SO THEY CAN LAST FOR YEARS

This is the major difference in your choice,

If you want the id to be remembered for long time, then you need to use cookies; otherwise if you just want the website to recognize the user for this visit only then sessions is the way to go.

Sessions are stored in a file your php server will generate. To remember which file is for which user, php will also set a cookie on the user's browser that holds this session file id so in their next visit php will read this file and reload the session.

Now php by default clears sessions every interval, and also naming convention of session make it auto expire. Also, browsers will not keep the cookie that holds the session id once the browser is closed or the history is cleared.

It's important to note that nowadays browsers also support another kind of storage engines such as LocalStorage, SessionStorage, and other webdb engines that javascript code can use to save data to your computer to remember you. If you open the javascript console inside Facebook, for example, and type "localStorage" you will see all the variables Facebook uses to remember you without cookies.


Actually, by default a session lasts until the user closes their browser, BUT this can be changed in the php.ini file by changing the 0 in session.cookie_lifetime = 0 to be the number of seconds you want the session to last, or by using session_set_cookie_params().
Further helpful information, such question that get many answers .. great, thanks again DOK!
Also keep in mind the single point of failure session files can create. When even the smallest dos style attack happens via proxy, ip switcher or zombies a session file is created on your server hard disk or ssd. If you can not keep up with the read writes your site will go down.
can anyone clafiry: "SESSIONS ENDS WHEN USER CLOSE HIS BROWSER" 1. what if the user navigates awya from the page.. then goes back without closing the browser. 2. what if they have several browser windows / tabs open pointing to the same site ? some web apps at work get confused in this situation, but i don't know what type of cookies they use.
@jcansell well, a cookie will not get confused by multi tabs or navigating away, in such case most probably these webapps used localstorage/session storage to save data using javascript
F
Fifi

Short answer

Rules ordered by priority:

Rule 1. Never trust user input : cookies are not safe. Use sessions for sensitive data.

Rule 2. If persistent data must remain when the user closes the browser, use cookies.

Rule 3. If persistent data does not have to remain when the user closes the browser, use sessions.

Rule 4. Read the detailed answer!

Source : https://www.lucidar.me/en/web-dev/sessions-or-cookies/

Detailed answer

Cookies

Cookies are stored on the client side (in the visitor's browser).

Cookies are not safe: it's quite easy to read and write cookie contents.

When using cookies, you have to notify visitors according to european laws (GDPR).

Expiration can be set, but user or browser can change it.

Users (or browser) can (be set to) decline the use of cookies.

Sessions

Sessions are stored on the server side.

Sessions use cookies (see below).

Sessions are safer than cookies, but not invulnarable.

Expiration is set in server configuration (php.ini for example).

Default expiration time is 24 minutes or when the browser is closed.

Expiration is reset when the user refreshes or loads a new page.

Users (or browser) can (be set to) decline the use of cookies, therefore sessions.

Legally, you also have to notify visitors for the cookie, but the lack of precedent is not clear yet.

The appropriate choice

Sessions use a cookie! Session data is stored on the server side, but a UID is stored on client side in a cookie. It allows the server to match a given user with the right session data. UID is protected and hard to hack, but not invulnarable. For sensitive actions (changing email or resetting password), do not rely on sessions neither cookies : ask for the user password to confirm the action.

Sensitive data should never be stored in cookies (emails, encrypted passwords, personal data ...). Keep in mind the data are stored on a foreign computer, and if the computer is not private (classroom or public computers) someone else can potentially read the cookies content.

Remember-me data must be stored in cookies, otherwise data will be lost when the user closes the browser. However, don't save password or user personal data in the 'remember-me' cookie. Store user data in database and link this data with an encrypted pair of ID / key stored in a cookie.

After considering the previous recommandations, the following question is finally what helps you choosing between cookies and sessions:

Must persistent data remain when the user closes the browser ?

If the answer is yes, use cookies.

If the answer is no, use sessions.


Thanks helpful .
w
whoan

when you save the #ID as the cookie to recognize logged in users, you actually are showing data to users that is not related to them. In addition, if a third party tries to set random IDs as cookie data in their browser, they will be able to convince the server that they are a user while they actually are not. That's a lack of security.

You have used cookies, and as you said you have already completed most of the project. besides cookie has the privilege of remaining for a long time, while sessions end more quickly. So sessions are not suitable in this case. In reality many famous and popular websites and services use cookie and you can stay logged-in for a long time. But how can you use their method to create a safer log-in process?

here's the idea: you can help the way you use cookies: If you use random keys instead of IDs to recognize logged-in users, first, you don't leak your primary data to random users, and second, If you consider the Random key large enough, It will be harder for anyone to guess a key or create a random one. for example you can save a 40 length key like this in User's browser: "KUYTYRFU7987gJHFJ543JHBJHCF5645UYTUYJH54657jguthfn" and it will be less likely for anyone to create the exact key and pretend to be someone else.


Nice explaination . I use GUID in token to recognise individual users.
C
Community

Actually, session and cookies are not always separate things. Often, but not always, session uses cookies.

There are some good answers to your question in these other questions here. Since your question is specifically about saving the user's IDU (or ID), I don't think it is quite a duplicate of those other questions, but their answers should help you.

cookies vs session

Cache VS Session VS cookies?

What is the difference between a Session and a Cookie?


A
Abel Callejo

TL;DR

Criteria / factors Sessions Cookies Epoch (start of existence) Created BEFORE an HTTP response Created AFTER an HTTP response Availability during the first HTTP request YES NO Availability during the succeeding HTTP requests YES YES Ultimate control for the data and expiration Server administrator End-user Default expiration Expires earlier than cookies Lasts longer than sessions Server costs Memory Memory Network costs None Unnecessary extra bytes Browser costs None Memory Security Difficult to hijack Easy to hijack Deprecation None Now discouraged in favor of the JavaScript "Web Storage"

Details

Advantages and disadvantages are subjective. They can result in a dichotomy (an advantage for some, but considered disadvantage for others). Instead, I laid out above the factors that can help you decide which one to pick.

Existence during the first HTTP request-and-response

Let's just say you are a server-side person who wants to process both the session and cookie. The first HTTP handshake will go like so:

Browser prepares the HTTP request -- SESSIONS: not available; COOKIES: not available Browser sends the HTTP request Server receives the HTTP request Server processes the HTTP request -- SESSIONS: existed; COOKIES: cast Server sends the HTTP response Browser receives the HTTP response Browser processes the HTTP response -- SESSIONS: not available; COOKIES: existed

In step 1, the browser have no idea of the contents of both sessions and cookies. In step 4, the server can have the opportunity to set the values of the session and cookies.

Availability during the succeeding HTTP requests-and-responses

Browser prepares the HTTP request -- SESSIONS: not available; COOKIES: available Browser sends the HTTP request Server receives the HTTP request Server processes the HTTP request -- SESSIONS: available; COOKIES: available Server sends the HTTP response Browser receives the HTTP response Browser processes the HTTP response -- SESSIONS: not available; COOKIES: available

Payload

Let's say in a single web page you are loading 20 resources hosted by example.com, those 20 resources will carry extra bytes of information about the cookies. Even if it's just a resource request for CSS or a JPG image, it would still carry cookies in their headers on the way to the server. Should an HTTP request to a JPG resource carry a bunch of unnecessary cookies?

Deprecation

There is no replacement for sessions. For cookies, there are many other options in storing data in the browser rather than the old school cookies.

Storing of user data

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.


M
Muhammad Sanaullah

I personally use both cookies and session.

Cookies only used when user click on "remember me" checkbox. and also cookies are encrypted and data only decrypt on the server. If anyone tries to edit cookies our decrypter able to detect it and refuse the request.

I have seen so many sites where login info are stored in cookies, anyone can just simply change the user's id and username in cookies to access anyone account.

Thanks,


佚名

Sessions allow you to store away individual pieces of information just like with cookies, but the data gets stored on the server instead of the client.


u
user3824494

Session and Cookie are not a same.

A session is used to store the information from the web pages. Normally web pages don’t have any memories to store these information. But using we can save the necessary information.

But Cookie is used to identifying the users. Using cookie we can store the data’s. It is a small part of data which will store in user web browser. So whenever user browse next time browser send back the cookie data information to server for getting the previous activities.

Credits : Session and Cookie


What if user disabled cookies? How cookie identify user?
W
Wasiq Mahmood WM

I will select Session, first of all session is more secure then cookies, cookies is client site data and session is server site data. Cookies is used to identify a user, because it is small pieces of code that is embedded my server with user computer browser. On the other hand Session help you to secure you identity because web server don’t know who you are because HTTP address changes the state 192.168.0.1 to 765487cf34ert8ded…..or something else numbers with the help of GET and POST methods. Session stores data of user in unique ID session that even user ID can’t match with each other. Session stores single user information in all pages of one application. Cookies expire is set with the help of setcookies() whereas session expire is not set it is expire when user turn off browsers.


J
Jay-R Joseph Gabunada

Cookies and Sessions are used to store information. Cookies are only stored on the client-side machine, while sessions get stored on the client as well as a server.

Session

A session creates a file in a temporary directory on the server where registered session variables and their values are stored. This data will be available to all pages on the site during that visit.

A session ends when the user closes the browser or after leaving the site, the server will terminate the session after a predetermined period of time, commonly 30 minutes duration.

Cookies

Cookies are text files stored on the client computer and they are kept of use tracking purposes. The server script sends a set of cookies to the browser. For example name, age, or identification number, etc. The browser stores this information on a local machine for future use.

When the next time the browser sends any request to the web server then it sends those cookies information to the server and the server uses that information to identify the user.


M
Md. Jamil Ahsan

The main difference between a Session and a Cookie is that Session data is stored on the server, whereas Cookies store data in the visitor’s browser.

Sessions are more secure than Cookies as it is stored in the server.

Data stored in Cookies can be stored for months or years, depending on the life span of the Cookie. But the data in the Session is lost when the web browser is closed.


K
Kamalakannan J

As others said, Sessions are clever and has more advantage of hiding the information from the client.

But Cookie still has at least one advantage, you can access your Cookies from Javascript(For example ngCookies). With PHP session you can't access it anywhere outside PHP script.


You can.. Not directly of course, hovever you can access it via some ajax request to script that returns session data. But I not sure do you should.
M
Megersa

A session is a group of information on the server that is associated with the cookie information. If you're using PHP you can check the session. save _ path location and actually "see sessions". A cookie is a snippet of data sent to and returned from clients. Cookies are often used to facilitate sessions since it tells the server which client handled which session. There are other ways to do this (query string magic etc) but cookies are likely most common for this.