为什么display_errors会更改HTTP状态代码?

时间:2012-07-10 20:16:39

标签: php http

正如许多其他问题所指出的,在php.ini中将display_errors变为Off会使Web服务器在遇到致命错误时回答状态代码为500内部服务器错误而不是200 OK。我设置了一个带有未定义函数的简单测试来解释行为:

的php.ini

display_errors = On

的index.php

<?php test();

给出:

Fatal error: Call to undefined function test()
in D:\xampp\htdocs\index.php on line 1

或者只是一个空白页面如果我像这样静音函数调用:

<?php @test();

在这两种情况下,答案标题如下:

HTTP/1.1 200 OK
Date: Tue, 10 Jul 2012 20:08:22 GMT
Server: Apache/2.2.21 (Win32) mod_ssl/2.2.21 OpenSSL/1.0.0e PHP/5.3.8 mod_perl/2.0.4 Perl/v5.10.1
X-Powered-By: PHP/5.3.8
Content-Length: 0
Keep-Alive: timeout=5, max=100
Connection: Keep-Alive
Content-Type: text/html

将php.ini更改为:

display_errors = Off

原因:

HTTP/1.0 500 Internal Server Error
Date: Tue, 10 Jul 2012 20:10:35 GMT
Server: Apache/2.2.21 (Win32) mod_ssl/2.2.21 OpenSSL/1.0.0e PHP/5.3.8 mod_perl/2.0.4 Perl/v5.10.1
X-Powered-By: PHP/5.3.8
Content-Length: 0
Connection: close
Content-Type: text/html

当display_errors关闭时,是否可以向我解释使web服务器以500响应的底层机制?

1 个答案:

答案 0 :(得分:7)

原因是使用display_errors = On,即使脚本中存在错误,您实际上也要求PHP为您提供合适的HTTP响应。可以把它想象成脚本和响应之间的附加层。它不再是你的脚本控制输出,它是PHP。

当您打开此选项时,您实际上在说,“如果出现错误,请仍然给我一个有效的HTTP响应页面(它甚至可能包含不错的标记),因为我会看到而不是我的日志。

将其设置为Off,HTTP响应应该没有意义,因此为500.如果启用,则会出现PHP错误,因此整个请求 500,即使你的脚本失败了。