为什么在使用会话时需要session_start? [英] Why session_start is needed when using session?

查看:91
本文介绍了为什么在使用会话时需要session_start?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么在使用$_SESSION之前需要session_start()时我可以不作任何准备就使用setcookie?我认为它们的工作原理是相似的.

解决方案

因为 setcookie () 定义要与其他HTTP标头一起发送的cookie .这与 session_start()所做的事情完全不同. 基于通过GET或POST请求传递或通过cookie传递的会话标识符创建会话或恢复当前会话.

第一个只是将一些内容添加到标头中,然后将其发送到浏览器中,而另一个则从$ _COOKIEs或$ _GET或$ _POST中获取会话ID .尝试在 session_save_path ,当发现将其值反序列化为$ _SESSION时,如果没有,则创建一个新会话,可能在过程中使用setcookie来设置会话ID.

请参见PHP手册中的关于会话的章节.


编辑就像@Felix在下面正确指出的一样,会话不一定保存在文件中.不过,它并不是那么重要,因为参数保持不变:session_start将查找并(重新)初始化您的会话数据,而setcookie只是按照名称的含义进行操作.

Why I can use setcookie without any preparation while need a session_start() before using $_SESSION?And I think works they do are similar.

解决方案

Because setcookie() defines a cookie to be sent along with the rest of the HTTP headers. That's a completely different thing than what session_start() does, e.g. creating a session or resuming the current one based on a session identifier passed via a GET or POST request, or passed via a cookie.

The first just adds something to the header and sends it to the browser, while the other gets the Session ID from $_COOKIEs or $_GET or $_POST and then tries finding the session file in the session_save_path and when found unserializing the values of it into $_SESSION and if not, create a new session, probably using setcookie in the process to set the Session Id.

See the chapter on Sessions in the PHP Manual.


Edit Like @Felix correctly points out below, the session is not necessarily saved in a file. It's not that important though, because the argument stays the same: session_start will find and (re-) initialize your session data, while setcookie just does what the name implies.

这篇关于为什么在使用会话时需要session_start?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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