duan1933 2011-08-31 16:20
浏览 67
已采纳

为什么这种组合使用cookie和会话有效? 困惑

I'm confused as to why this is working;

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

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'];

It prints string.

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!

  • 写回答

3条回答 默认 最新

  • dongma0722 2011-08-31 16:32
    关注

    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(), 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.)

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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 求螺旋焊缝的图像处理
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面
  • ¥15 itunes恢复数据最后一步发生错误
  • ¥15 关于#windows#的问题:2024年5月15日的win11更新后资源管理器没有地址栏了顶部的地址栏和文件搜索都消失了
  • ¥100 H5网页如何调用微信扫一扫功能?
  • ¥15 讲解电路图,付费求解