我应该何时何地使用 session_start? [英] When and where should I use session_start?

查看:31
本文介绍了我应该何时何地使用 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_start,除非您使用 session_write_close 将其关闭.
  • 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 use session_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 发送到浏览器发送内容.
  • 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 所提到的,创建新会话需要一些成本,因此如果您的网站正忙于处理合法或恶意流量,您可能希望在根本不启动的情况下提供一些着陆页或错误消息.

在那之后,它变成了样式和架构的问题,但涵盖上述大部分内容的经验法则是如果您确定页面需要它,请尽快".

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屋!

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