如何正确控制http状态码?
我在 CodeIgniter 中测试 400 错误处理时遇到了一件奇怪的事情。
消息:无法修改标头信息 - 标头已由(输出开始于...)发送
并且http状态代码始终为200,最后我发现.然后我检查了 php 文档,发现了这个:
header() 用于发送原始 HTTP 标头。有关 HTTP 标头的更多信息,请参阅 » HTTP/1.1 规范。
请记住,在发送任何实际输出之前,必须调用 header(),无论是通过普通 HTML 标记、文件中的空行还是从 PHP。
那么如何在 php 中正确设置 http 状态码以确保它位于任何输出之前? 我是 php 编程新手。谢谢你的回复!
I met a strange thing when test the 400 error handling in CodeIgniter.
Message: Cannot modify header information - headers already sent by (output started at ...)
And the http status code is always 200, finally I found that there is a new line before <?php ...
. Then I checked the php doc, found this:
header() is used to send a raw HTTP header. See the » HTTP/1.1 specification for more information on HTTP headers.
Remember that header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP.
So how to set the http status code properly in php to make sure it is before any output?
I am new to php programming. Thanks for you reply!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在执行任何创建输出的操作(包括将空格字符放在
部分之外)之前,您需要调用
header()
。You call
header()
before you do anything that creates output (including putting whitespace characters outside<?php
sections).正如其他人所说,您必须在任何其他输出之前发送标头(即使用
header()
)。经常发生的一件事是,有时您在 PHP 结束标记之后无意中包含了换行符的文件。例如,
为了减少这种情况的发生,您可以故意省略 PHP 结束标记。该文件将被解析为 PHP 直到最后,因此从包含的文件发送虚假换行符或空格的可能性要小得多。
根据您的编辑器,您还可以将其设置为显示空白(回车、空格、制表符),这在尝试消除脚本中的意外输出时会有所帮助(例如,Eclipse 和 Notepad++ 都可以做到这一点)。
As others have said, you must send headers (i.e. use
header()
) before any other output.One thing that can often happen is that sometimes you include files that inadvertently have newlines in them, after the closing PHP tag. e.g.
In order to reduce the chances of this, you can deliberately leave out the closing PHP tag. The file will be parsed as PHP until the end, so there's far less chance of spurious newlines or spaces being sent from an included file.
Depending on your editor, you can also set it to show whitespace (carriage returns, spaces, tabs), which can help when trying to eliminate unexpected output from your scripts (Eclipse and Notepad++ can both do it, for example).
在将任何内容返回给访问者之前,请使用
header()
函数。如果您在调用
header()
之前无法确定返回内容的位置,请在 PHP 脚本的开头添加ob_start()
函数。虽然它会起作用,但我仍然建议您清理代码并且不要让数据在应该输出之前输出。更好的做法是始终了解自己的代码中发生了什么,而不是退回到补丁解决方案。
Please your
header()
function before anything is ever returned to the visitor.If you are unable to determine where something is being returned before calling
header()
, add anob_start()
function in the beginning of the PHP script.Though it will work, I still suggest you to clean up your code and to not let data be outputted before it should. It is a better practice to always know what is happening within your own code and not to fall back to patch solutions.