PHP 中的 Sessions 和 Cookies 有什么区别?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6339783/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 00:05:15  来源:igfitidea点击:

What is the difference between Sessions and Cookies in PHP?

phpsessioncookiessession-statesession-cookies

提问by Harsh

What is the distinction between Sessionsand Cookiesin PHP?

PHP 中的SessionsCookies 有什么区别?

回答by Quentin

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

cookie 是浏览器存储的一些数据,每次请求都会发送到服务器。

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)

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

回答by toomasr

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

Cookie用于识别会话。访问任何使用 cookie 的站点,然后调出 Chrome 检查元素,然后是网络或 FireBug(如果使用 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.

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

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.

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

A sessionis 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.

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

Screenshot of a Cookie

Cookie 的屏幕截图

回答by Armin John

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.

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

Sessions are more secure than cookies as it is stored in server. Cookie can be turned off from browser.

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

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.

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

回答by seand

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.

会话是在服务器上维护的一块数据,用于维护 HTTP 请求之间的状态。HTTP 从根本上说是一种无状态协议;会话用于赋予它状态。

A cookie is a snippet of data sent to and returned from clients. Cookies are often used to facilitatesessions 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.

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

回答by Elangovan

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

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

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

Cookie 易于访问,因此安全较低。setcookie() 函数必须出现在 tag 之前

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

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

回答by user7166162

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.

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

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.

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

回答by Sam-T

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.

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

Did I get this right?

我做对了吗?

回答by Basj

Cookie

曲奇饼

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

  • can be set from PHP with setcookieand 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=baris still there. Now close the browser and reopen it, re-visit the same website, open the Console ; you will see document.cookieis 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)
    
  • 是浏览器中保存的少量数据(客户端)

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

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

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

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

  • 存储在浏览器中的 cookie 在同一网站的每个请求的标头中发送到服务器(请参阅 参考资料Cookie)。例如,您可以通过打开开发者工具 > 网络在 Chrome 中看到这一点,单击请求,请参阅Headers

    在此处输入图片说明

  • 可以在客户端读取 document.cookie

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

  • 奖励:它也可以用 PHP 以外的其他语言设置/获取。带有“瓶子”微框架的 Python 示例(另请参见此处):

    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 PHPSESSIDcookie 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 databut 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 sessionsif you want to use your own database + IDs and send an ID/token to the client with a traditional Cookie

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

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

  • 在 PHP 中,whensession_start();被调用:

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

      在此处输入图片说明

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

    • 您可以使用以下命令在客户端查看会话 ID document.cookie

      在此处输入图片说明

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

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

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

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

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

    在此处输入图片说明

  • 因此,会话对于存储您不想被客户端看到或修改的数据很有用

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