PHP 中的 Session 和 Cookie 有什么区别?

发布于 2024-11-15 10:36:44 字数 70 浏览 2 评论 0原文

PHP 中的SessionCookies 有什么区别?

What is the distinction between Sessions and Cookies in PHP?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

祁梦 2024-11-22 10:36:44

Cookie 是浏览器存储的一点数据,并随每个请求发送到服务器。

会话是存储在服务器上并与给定用户关联的数据集合(通常通过包含 ID 代码的 cookie)

A cookie is a bit of data stored by the browser and sent to the server with every request.

A session is a collection of data stored on the server and associated with a given user (usually via a cookie containing an id code)

走过海棠暮 2024-11-22 10:36:44

Cookie 用于识别会话。访问任何使用 cookie 的网站,然后拉出 Chrome 检查元素,然后拉出网络或 FireBug(如果使用 Firefox)。

您可以看到有一个标头发送到服务器并且也收到了称为 Cookie 的标头。通常它包含一些可在服务器上用来识别会话的个人信息(如 ID)。这些 cookie 保留在您的计算机上,您的浏览器负责将它们仅发送到用其标识的域。

如果没有 cookie,那么您将通过 GET 或 POST 发送每个请求的唯一 ID。 Cookie 类似于静态 ID,会在您的计算机上保留一段时间。

会话是服务器上与 cookie 信息关联的一组信息。如果您使用 PHP,您可以检查 session.save_path 位置并实际“查看会话”。它们要么是服务器文件系统上的文件,要么是数据库中的文件。

Cookie 的屏幕截图

Cookies are used to identify sessions. Visit any site that is using cookies and pull up either Chrome inspect element and then network or FireBug if using Firefox.

You can see that there is a header sent to a server and also received called Cookie. Usually it contains some personal information (like an ID) that can be used on the server to identify a session. These cookies stay on your computer and your browser takes care of sending them to only the domains that are identified with it.

If there were no cookies then you would be sending a unique ID on every request via GET or POST. Cookies are like static id's that stay on your computer for some time.

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". They are either files on the server filesystem or backed in a database.

Screenshot of a Cookie

南渊 2024-11-22 10:36:44

会话和 cookie 之间的主要区别在于会话数据存储在服务器上,而 cookie 将数据存储在访问者的浏览器中。

会话比 cookie 更安全,因为它存储在服务器中。可以从浏览器中关闭 Cookie。

存储在 cookie 中的数据可以存储数月或数年,具体取决于 cookie 的生命周期。但是当网络浏览器关闭时,会话中的数据就会丢失。

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 server. Cookie can be turned off from browser.

Data stored in cookie 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.

兮颜 2024-11-22 10:36:44

Cookie

  • 是保存在浏览器(客户端)中的少量数据

  • 可以通过 PHP 设置 setcookie 然后将被发送到客户端的浏览器( HTTP 响应头 Set-cookie)

  • 可以在 Javascript 中直接在客户端设置:document.cookie = 'foo=bar';

  • 如果不设置过期日期,默认情况下,浏览器关闭时就会过期。
    示例:继续 http://example.com,打开控制台,执行 document.cookie = 'foo=酒吧';。关闭选项卡,重新打开同一网站,打开控制台,执行 document.cookie:您将看到 foo=bar 仍然存在。现在关闭浏览器并重新打开,重新访问同一网站,打开控制台;你会看到document.cookie为空。

  • 您还可以设置“浏览器关闭时删除”以外的精确到期日期。

  • 存储在浏览器中的cookie会在同一网站的每个请求的标头中发送到服务器(请参阅Cookie)。例如,您可以使用 Chrome 打开 开发人员工具 > 来查看此内容。网络,点击请求,查看标头

    在此处输入图像描述

  • 可以通过 document.cookie 在客户端读取p>

  • 可以通过$_COOKIE['foo']在服务器端读取

  • 奖励:它还可以使用 PHP 以外的其他语言来设置/获取。使用“bottle”微框架的 Python 示例(另请参阅此处):< /p>

    from Bottle import 获取、运行、请求、响应
    @得到('/')
    定义索引():
        if request.get_cookie("访问过"):
            return“欢迎回来!很高兴再次见到你”
        别的:
            response.set_cookie("访问过", "是")
            return“你好!很高兴认识你”
    运行(主机='localhost',端口=8080,调试=True,重新加载器=True)
    

会话

  • 是与保存的浏览器会话相关的一些数据服务器端

  • 每个服务器-side 语言可以以不同的方式实现它

  • session_start(); 被调用:

    • 服务器生成一个随机ID,例如jo96fme9ko0f85cdglb3hl6ah6
    • 文件保存在服务器上,包含数据:例如/var/lib/php5/sess_jo96fme9ko0f85cdglb3hl6ah6
    • 会话 ID 在 HTTP 响应标头中发送到客户端,使用上面详述的传统 cookie 机制Set-Cookie: PHPSESSID=jo96fme9ko0f85cdglb3hl6ah6;路径=/

      在此输入图像描述

      (也可以通过 URL 而不是 cookie 发送,但不是默认行为)

    • 您可以通过 document.cookie 在客户端查看会话 ID:

      在此输入图像描述

  • PHPSESSID cookie设置没有过期日期,因此当浏览器关闭时它就会过期。因此,当浏览器关闭/重新打开时,“会话”将不再有效。

  • 可以通过 $_SESSION 在 PHP 中设置/读取

  • 客户端 看不到会话数据,只看到 ID:在 index.php 中执行此操作:

    <前><代码>

    在客户端看到的唯一内容是(如上所述)会话 ID:

    在此处输入图像描述

  • ,会话可用于存储您不希望客户端看到或修改的数据

  • 如果您想使用自己的数据库+ ID 并使用传统 Cookie 向客户端发送 ID/令牌,则可以完全避免使用会话

Cookie

  • is a small amount of data saved in the browser (client-side)

  • can be set from PHP with setcookie and then will be sent to the client's browser (HTTP response header Set-cookie)

  • can be set directly client-side in Javascript: document.cookie = 'foo=bar';

  • if no expiration date is set, by default, it will expire when the browser is closed.
    Example: go on http://example.com, open the Console, do document.cookie = 'foo=bar';. Close the tab, reopen the same website, open the Console, do document.cookie: you will see foo=bar is still there. Now close the browser and reopen it, re-visit the same website, open the Console ; you will see document.cookie is empty.

  • you can also set a precise expiration date other than "deleted when browser is closed".

  • the cookies that are stored in the browser are sent to the server in the headers of every request of the same website (see Cookie). You can see this for example with Chrome by opening Developer tools > Network, click on the request, see Headers:

    enter image description here

  • can be read client-side with document.cookie

  • can be read server-side with $_COOKIE['foo']

  • Bonus: it can also be set/get with another language than PHP. Example in Python with "bottle" micro-framework (see also here):

    from bottle import get, run, request, response
    @get('/')
    def index():
        if request.get_cookie("visited"):
            return "Welcome back! Nice to see you again"
        else:
            response.set_cookie("visited", "yes")
            return "Hello there! Nice to meet you"
    run(host='localhost', port=8080, debug=True, reloader=True)
    

Session

  • is some data relative to a browser session saved server-side

  • each server-side language may implement it in a different way

  • in PHP, when session_start(); is called:

    • a random ID is generated by the server, e.g. jo96fme9ko0f85cdglb3hl6ah6
    • a file is saved on the server, containing the data: e.g. /var/lib/php5/sess_jo96fme9ko0f85cdglb3hl6ah6
    • the session ID is sent to the client in the HTTP response headers, using the traditional cookie mechanism detailed above: Set-Cookie: PHPSESSID=jo96fme9ko0f85cdglb3hl6ah6; path=/:

      enter image description here

      (it can also be be sent via the URL instead of cookie but not the default behaviour)

    • you can see the session ID on client-side with document.cookie:

      enter image description here

  • the PHPSESSID cookie is set with no expiration date, thus it will expire when the browser is closed. Thus "sessions" are not valid anymore when the browser is closed / reopened.

  • can be set/read in PHP with $_SESSION

  • the client-side does not see the session data but only the ID: do this in index.php:

    <?php
    session_start();
    $_SESSION["abc"]="def";
    ?>
    

    The only thing that is seen on client-side is (as mentioned above) the session ID:

    enter image description here

  • because of this, session is useful to store data that you don't want to be seen or modified by the client

  • you can totally avoid using sessions if you want to use your own database + IDs and send an ID/token to the client with a traditional Cookie

剪不断理还乱 2024-11-22 10:36:44

会话是在服务器上维护的数据块,用于维护 HTTP 请求之间的状态。 HTTP 本质上是一个无状态协议;会话用于赋予其状态性。

cookie 是发送给客户端和从客户端返回的数据片段。 Cookie 通常用于促进会话,因为它告诉服务器哪个客户端处理了哪个会话。还有其他方法可以做到这一点(查询字符串魔术等),但 cookie 可能是最常见的。

A session is a chunk of data maintained at the server that maintains state between HTTP requests. HTTP is fundamentally a stateless protocol; sessions are used to give it statefulness.

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.

故事↓在人 2024-11-22 10:36:44

Cookie 以文本文件格式存储在浏览器中。它存储的数据量有限,最多 4kb[4096bytes]。单个 Cookie 不能保存多个值,但我们可以可以有多个 cookie。

Cookie 很容易访问,因此安全性较低。 setcookie() 函数必须出现在标签之前

Session存储在服务器端。Session没有存储限制。Session可以保存多个变量。由于它们不易访问,因此比cookie更安全。

Cookies are stored in browser as a text file format.It stores limited amount of data, up to 4kb[4096bytes].A single Cookie can not hold multiple values but yes we can have more than one cookie.

Cookies are easily accessible so they are less secure. The setcookie() function must appear BEFORE the tag.

Sessions are stored in server side.There is no such storage limit on session .Sessions can hold multiple variables.Since they are not easily accessible hence are more secure than cookies.

一曲爱恨情仇 2024-11-22 10:36:44

所有这些解释中缺少的一部分是 Cookie 和会话如何通过 SessionID cookie 链接。 Cookie 在客户端和服务器之间来回传递 - 服务器通过 Cookie 的会话 ID 部分链接用户(及其会话)。
您也可以通过 url 发送 SessionID(不是最佳实践)——以防客户端禁用 cookie。

我做对了吗?

One part missing in all these explanations is how are Cookies and Session linked- By SessionID cookie. Cookie goes back and forth between client and server - the server links the user (and its session) by session ID portion of the cookie.
You can send SessionID via url also (not the best best practice) - in case cookies are disabled by client.

Did I get this right?

丢了幸福的猪 2024-11-22 10:36:44

会话

会话用于维持服务器和用户之间的对话。
它更安全,因为它存储在服务器上,我们无法轻易访问它。
它将 cookie 嵌入用户计算机上。它存储无限的数据。

Cookie

Cookie 存储在本地计算机上。基本上,它维护用户身份,这意味着它跟踪访客记录。它的安全性不如会话。
它存储的数据量有限,并且维护时间有限。

Session

Session is used for maintaining a dialogue between server and user.
It is more secure because it is stored on the server, we cannot easily access it.
It embeds cookies on the user computer. It stores unlimited data.

Cookies

Cookies are stored on the local computer. Basically, it maintains user identification, meaning it tracks visitors record. It is less secure than session.
It stores limited amount of data, and is maintained for a limited time.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文