PHP:防止标头和会话开始
我已经构建了自己的教育 MVC 框架来了解有关 PHP OOP 的更多信息,我当然已经了解了,但目前我已陷入困境。我需要在项目的大部分时间使用会话,但还需要在某个页面将文件流式传输给用户。
当我在进入控制器之前默认调用 session_start()
时,当我需要从控制器内部流式传输文件时,我会看到臭名昭著的 Headers already sent
抛出在我的脸上给用户。很有逻辑。
当我在控制器内进行会话修改时,我需要事先调用 session_start()
,但那时控制器显然没有加载,我的框架无法判断是否它应该或不调用session_start()
。 创建一个包含不需要会话的控制器名称白名单的文件似乎相当原始。
当我需要流式传输文件时,摆脱会话的适当方法是什么?
I've built my own educational MVC framework to learn more about PHP OOP, which I certainly have, but for the moment I have gotten myself into a pickle. I need to use sessions throughout most of the project, but also need to stream a file to the user at a certain page.
As I call session_start()
by default before getting into my controller, I get the infamous Headers already sent
thrown in my face when I need to stream a file from inside the controller to the user. Pretty logical.
As I make the session modification inside the controllers, I need the session_start()
to be called in beforehand, but at that time, the controller obviously isn't loaded and there's no way my framework could tell whether It should call the session_start()
or not.
Creating a file with a white list of controller names that doesn't need sessions seems quite primitive.
What would be an appropriate way to get rid of sessions when I need to stream a file?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
在我看来,启动会话属于引导程序,而不是对象。
我倾向于总是从引导程序的第一行开始,无论当前脚本是否需要它。对性能的影响可能不存在或很小。
Starting the session belongs in the bootstrap, not in an object IMO.
I would tend to always start in one of the first lines of the bootstrap, regardless whether it will be needed in the current script or not. Performance implications are likely to be non-existent or minimal.
使用面向对象编程。您的控制器必须以某种方式扩展基础 AbstractController。因此,添加一个默认返回 true 的虚拟方法“NeedsSession()”。现在,为不需要会话的控制器重写此方法。这样更干净。
Use OOP. Your controllers must somehow extend a base AbstractController. So, add a virtual method "NeedsSession()" that returns true by default. Now, override this method for the controllers that don't need a session. It's cleaner this way.
当您发送任何输出时,如果您的文件之一在封闭的标记标头将发送到服务器之后包含任何空格,则意味着您也在发送标头。检查您的文件是否执行此操作
session_start
必须在将任何标头发送到服务器之前调用。中间包含的文件中不应有任何空格,请仔细检查文件是否在开头或结尾处包含任何空格When you send any output means you are sending the header as well if one of the your file contain any white space after the enclosing tag header will be sent to server . Check your files if they does this thing
session_start
must be called before any header sent to server. There should not be any space in the files which are included in between double check your files if they contain any space at starting or the end如果您的所有请求都指向 index.php 文件,那么您应该在其中开始会话(
标头已发送
问题应该消失)。记住文件中的 UTF-8 编码(无 BOM)If all of your requests are leading to index.php file, that's where you should start your session (
Headers already sent
problem should disappear). Remember about UTF-8 encoding in your file (without BOM)