我应该在何时何地使用session_start? [英] When and where should I use session_start?
问题描述
我应该在何时何地在PHP中使用session_start()
?
Exactly when and where should I use session_start()
in PHP?
例如,假设我有一个登录脚本,该脚本设置了一个会话变量以告知用户是否已登录.然后必须将session_start()
放在脚本顶部,还是仅在实际设置之前会话变量是否成功登录?
For example, say I have a login script that sets a session variable to tell whether or not the user is logged in. Must I then put the session_start()
at the top of the script, or only right before I actually set the session variable if the login was successful?
<?php
// session_start(); here?
if (login($username, $password)) {
// session_start(); or here?
$_SESSION["username"] = $username;
}
?>
根据w3schools的说法,这是另一种情况
Another case is this, according to w3schools
注意:session_start()函数必须是文档中的第一件事.在任何HTML标记之前.
Note: The session_start() function must be the very first thing in your document. Before any HTML tags.
推荐答案
正如其他人所说,您必须要做的绝对要求是:
As others have said, the absolute requirements of what you must do are:
- 在读取或写入
$_SESSION
之前,必须先运行session_start
(否则它将只是一个普通数组,不会保存在任何地方). - 除非在每个脚本之间执行
session_write_close
来将其关闭,否则在一次脚本执行(页面加载)期间不得运行两次session_start
.
- You must run
session_start
before you read or write to$_SESSION
(otherwise it will just be an ordinary array and not saved anywhere). - You must not run
session_start
twice during a single script execution (page load) unless you usesession_write_close
to close it in between.
还有一条额外的规则,从技术上讲有例外,但最好将其视为绝对规则:
There is an extra rule that technically has exceptions, but is best treated as absolute:
- 在编写任何输出(
echo
,PHP块外的HTML等)之后,请勿启动会话,因为如果服务器已经开始发送内容,则PHP可能无法将cookie发送到浏览器./li>
- Do not start the session after you have written any output (
echo
, HTML outside PHP blocks, etc), because PHP may not be able to send cookies to the browser if the server has already started sending the content.
您可能要避免开始会话有两个原因:
There are two reasons you might want to avoid starting the session:
- PHP在打开会话时将其锁定,以避免两个进程将冲突的数据写入其中,因此,如果一次有多个请求发生,则除非它们确实需要,否则它们将避免彼此等待.例如,如果您正在响应AJAX请求,并且不需要会话中的任何数据,请不要打开它.
- 如symcbean所述,创建新会话需要一定的成本,因此,如果您的站点忙于合法流量或恶意流量,则可能需要提供一些登陆页面或错误消息而根本不启动它. li>
此后,这成为样式和体系结构的问题,但是涵盖以上大部分内容的经验法则是如果确定页面需要,请尽快".
After that, it becomes a matter of style and architecture, but the rule of thumb that covers most of the above is "as soon as possible, if you're sure the page needs it".
这篇关于我应该在何时何地使用session_start?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!