php - 捕获 PHP fatal error

标签 php http-status-codes

我有一个启用了 restful 的 Web 服务站点,因此其他网站/ajax 脚本可以调用该站点以获取/设置数据。但是,每当 Web 服务站点以某种方式返回 PHP fatal error 时,返回的 HTTP 状态是 200 而不是 500。有没有办法修复它,以便在发生 fatal error 时返回 500 而不是 200?或者,如果不可能,我该如何更改我的客户端以识别网络服务返回的 fatal error ?

最佳答案

PHP 确实在发生 fatal error 时发送 HTTP 500。
让我在 this PHP bug-report 中引用一条评论(一个 xdebug 错误阻止了这种行为):

It does happen. It requires that:

1) display_errors = off
2) No headers have been sent yet by the time the error happens
3) Status is 200 at that time.

<?
    ini_set('display_errors', 0); 
    foobar();
    // This will return a http 500
?>

您可以使用 shutdown function 捕获 fatal error 和 error_get_last :

register_shutdown_function(function() {
    $lastError = error_get_last();

    if (!empty($lastError) && $lastError['type'] == E_ERROR) {
        header('Status: 500 Internal Server Error');
        header('HTTP/1.0 500 Internal Server Error');
    }
});

关于php - 捕获 PHP fatal error ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2331582/

相关文章:

jsf-2 - 如何使用 JSF 设置 HTTP 状态码?

cloud-foundry - 内部服务器错误被映射到 302 Found,重定向到 Swisscom CloudFoundry 上的 "/offline_pages/"

java - Jersey Web 服务发送 415 状态代码

php - zend 模块特定配置的问题

php - 我怎样才能阻止 Symfony 截断我的 POSTed 对象?

php - 从交叉引用表中获取唯一值

rest - 更改 Genexus 过程 Rest 中的 HTTP 状态代码

seo - Http 状态代码 301 到返回 410 的页面

PHP 备份脚本超时

php - 如何使用ajax post将JSON数据传递给php