Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

http status codes - Catch PHP Fatal Error

I have a web service site that is restful enabled, so other websites/ajax script can make a call to the site to get/set data. However, whenever the web service site somehow returns a PHP fatal error, the HTTP status that is returned is 200 instead of 500. Is there a way to fix it so that whenever a fatal error occurs, returns 500 instead of 200? Or, if it is not possible, how can I change my client to recognize the fatal error returned by the webservice?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

PHP does send a HTTP 500 on a Fatal error.
Let me cite a comment in this PHP bug-report (a xdebug bug prevents this behavior):

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
?>

You can catch fatal errors with a shutdown function and 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');
    }
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...