什么是 cookie 和会话,它们之间是如何相互关联的?

我正在努力以专业的方式理解 Cookie 和会议。 我知道当浏览器连接到服务器时,服务器“请求”浏览器在客户端浏览器 Cookie 文件夹中“粘贴”一个带有“ phpsessid”的 Cookie。

现在我们有了“ phpsessid”,如果客户端进入服务器,浏览器向服务器发送“ phpsessid”,服务器查看 tmp 文件夹,如果我们有一个匹配,它会返回用户为这个客户端拥有的所有数据,但我对这个过程有点困惑。

如果有人能帮助我理解创建会话和 cookie 的过程——幕后发生了什么,我将不胜感激。

70763 次浏览

Let's go through this:

Cookies and sessions are both ways to preserve the application's state between different requests the browser makes. It's thanks to them that, for instance, you don't need to log in every time you request a page on StackOverflow.

Cookies

Cookies are small bits of data, (maximum of 4KB long), which hold data in a key=value pairs:

name=value; name2=value2

These are set either by JavaScript, or via the server using an HTTP header.

Cookies have an expiry datetime set, example using HTTP headers:

Set-Cookie: name2=value2; Expires=Wed, 19 Jun 2021 10:18:14 GMT

Which would cause the browser to set a cookie named name2 with a value of value2, which would expire in about 9 years.

Cookies are considered highly insecure because the user can easily manipulate their content. That's why you should always validate cookie data. Don't assume what you get from a cookie is necessarily what you expect.

Cookies are usually used to preserve login state, where a username and a special hash are sent from the browser, and the server checks them against the database to approve access.

Cookies are also often used in sessions creation.

Sessions

Sessions are slightly different. Each user gets a session ID, which is sent back to the server for validation either by cookie or by GET variable.

Sessions are usually short-lived, which makes them ideal in saving temporary state between applications. Sessions also expire once the user closes the browser.

Sessions are considered more secure than cookies because the variables themselves are kept on the server. Here's how it works:

  1. Server opens a session (sets a cookie via HTTP header)
  2. Server sets a session variable.
  3. Client changes page
  4. Client sends all cookies, along with the session ID from step 1.
  5. Server reads session ID from cookie.
  6. Server matches session ID from a list in a database (or memory etc).
  7. Server finds a match, reads variables which are now available on $_SESSION superglobal.

If PHP does not find a match, it will start a new session, and repeat the steps from 1-7.

You can store sensitive information on a session because it is kept on the server, but be aware that the session ID can still be stolen if the user, let's say, logged in over an insecure WiFi. (An attacker can sniff the cookies, and set it as its own, he won't see the variables themselves, but the server will identify the attacker as the user).


That's the gist of it. You can learn more on the PHP manual on both subjects.