为什么Cookie和会话的这种结合使用有效?困惑 [英] Why is this combined usage of cookies and sessions working? Confused

查看:80
本文介绍了为什么Cookie和会话的这种结合使用有效?困惑的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对为什么它起作用感到困惑;

setcookie("user", $user_id, time()+604800);
session_start();
$_SESSION['user_id'] = "string";

即使 setcookie()不包含任何引用到 $ _ SESSION ['user_id'] 时,当我从另一个页面的 $ _ SESSION ['user_id'] 回显代码:

Even though setcookie() contains no reference to $_SESSION['user_id'], when I echo $_SESSION['user_id'] from another page with the code:

session_start();
echo $_SESSION['user_id'];

它会打印 string

给我的印象是 setcookie()必须引用 $ _ SESSION 以便可以从任何页面调用它的键?

I was under the impression that setcookie() had to reference a $_SESSION key in order for it to be called from any page?

也许我不太了解,但是我只是想确保我理解为什么这样做在实现它之前,我宁愿不要因为使用不当而过错。

Perhaps I'm well off base, but I just want to make sure I understand why this is working before I implement it, as I'd rather it not fault because of incorrect usage.

任何帮助,评论,建议和解释将不胜感激!

Any help, comments, advice and explanations will be appreciated!

推荐答案

setcookie()发送一个浏览器使用通用Cookie,而 session_start()初始化会话将会话cookie发送到浏览器。使用 setcookie(),您可以发送Cookie中所需的任何内容,例如在两次访问之间可以记住的用户名和密码,或任意文本。请注意,所有这些都直接存储在cookie本身中,并且可以由用户操纵,因此不应被信任。

setcookie() sends a generic cookie to the browser while session_start() initializes a session and sends a session cookie to the browser. With setcookie(), you can send whatever you want in the cookie, such as the user's username and password to be remembered between visits, or any arbitrary text. Note that all of this is stored right in the cookie itself and can be manipulated by the user and therefore should not be trusted.

With session_start( ),所有内容都在服务器端处理。 Cookie中发送的唯一内容是会话标识符。会话数据不能被浏览器直接操纵。 PHP还处理冲突预防,数据存储(默认情况下是纯文本文件,只能由root用户查看并存储在/ tmp中)和到期(即使cookie是由浏览器操纵的)。

With session_start(), on the other hand, everything is handled server-side. The only thing sent in the cookie is the session identifier. Session data cannot be directly manipulated by the browser. PHP also handles collision prevention, data storage (which by default is a plain text file viewable only by root and stored in /tmp) and expiration (even if the cookie is manipulated by the browser.)

本质上,即使这些功能相似,它们都向浏览器发送cookie,但它们的作用完全不同。

Essentially, even though these functions are similar in that they both send a cookie to the browser, they both serve completely different purposes.

这篇关于为什么Cookie和会话的这种结合使用有效?困惑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆