Php отправить ошибку 500

You may use the following function to send a status change:

function header_status($statusCode) {
    static $status_codes = null;

    if ($status_codes === null) {
        $status_codes = array (
            100 => 'Continue',
            101 => 'Switching Protocols',
            102 => 'Processing',
            200 => 'OK',
            201 => 'Created',
            202 => 'Accepted',
            203 => 'Non-Authoritative Information',
            204 => 'No Content',
            205 => 'Reset Content',
            206 => 'Partial Content',
            207 => 'Multi-Status',
            300 => 'Multiple Choices',
            301 => 'Moved Permanently',
            302 => 'Found',
            303 => 'See Other',
            304 => 'Not Modified',
            305 => 'Use Proxy',
            307 => 'Temporary Redirect',
            400 => 'Bad Request',
            401 => 'Unauthorized',
            402 => 'Payment Required',
            403 => 'Forbidden',
            404 => 'Not Found',
            405 => 'Method Not Allowed',
            406 => 'Not Acceptable',
            407 => 'Proxy Authentication Required',
            408 => 'Request Timeout',
            409 => 'Conflict',
            410 => 'Gone',
            411 => 'Length Required',
            412 => 'Precondition Failed',
            413 => 'Request Entity Too Large',
            414 => 'Request-URI Too Long',
            415 => 'Unsupported Media Type',
            416 => 'Requested Range Not Satisfiable',
            417 => 'Expectation Failed',
            422 => 'Unprocessable Entity',
            423 => 'Locked',
            424 => 'Failed Dependency',
            426 => 'Upgrade Required',
            500 => 'Internal Server Error',
            501 => 'Not Implemented',
            502 => 'Bad Gateway',
            503 => 'Service Unavailable',
            504 => 'Gateway Timeout',
            505 => 'HTTP Version Not Supported',
            506 => 'Variant Also Negotiates',
            507 => 'Insufficient Storage',
            509 => 'Bandwidth Limit Exceeded',
            510 => 'Not Extended'
        );
    }

    if ($status_codes[$statusCode] !== null) {
        $status_string = $statusCode . ' ' . $status_codes[$statusCode];
        header($_SERVER['SERVER_PROTOCOL'] . ' ' . $status_string, true, $statusCode);
    }
}

You may use it as such:

<?php
header_status(500);

if (that_happened) {
    die("that happened")
}

if (something_else_happened) {
    die("something else happened")
}

update_database();

header_status(200);

You may use the following function to send a status change:

function header_status($statusCode) {
    static $status_codes = null;

    if ($status_codes === null) {
        $status_codes = array (
            100 => 'Continue',
            101 => 'Switching Protocols',
            102 => 'Processing',
            200 => 'OK',
            201 => 'Created',
            202 => 'Accepted',
            203 => 'Non-Authoritative Information',
            204 => 'No Content',
            205 => 'Reset Content',
            206 => 'Partial Content',
            207 => 'Multi-Status',
            300 => 'Multiple Choices',
            301 => 'Moved Permanently',
            302 => 'Found',
            303 => 'See Other',
            304 => 'Not Modified',
            305 => 'Use Proxy',
            307 => 'Temporary Redirect',
            400 => 'Bad Request',
            401 => 'Unauthorized',
            402 => 'Payment Required',
            403 => 'Forbidden',
            404 => 'Not Found',
            405 => 'Method Not Allowed',
            406 => 'Not Acceptable',
            407 => 'Proxy Authentication Required',
            408 => 'Request Timeout',
            409 => 'Conflict',
            410 => 'Gone',
            411 => 'Length Required',
            412 => 'Precondition Failed',
            413 => 'Request Entity Too Large',
            414 => 'Request-URI Too Long',
            415 => 'Unsupported Media Type',
            416 => 'Requested Range Not Satisfiable',
            417 => 'Expectation Failed',
            422 => 'Unprocessable Entity',
            423 => 'Locked',
            424 => 'Failed Dependency',
            426 => 'Upgrade Required',
            500 => 'Internal Server Error',
            501 => 'Not Implemented',
            502 => 'Bad Gateway',
            503 => 'Service Unavailable',
            504 => 'Gateway Timeout',
            505 => 'HTTP Version Not Supported',
            506 => 'Variant Also Negotiates',
            507 => 'Insufficient Storage',
            509 => 'Bandwidth Limit Exceeded',
            510 => 'Not Extended'
        );
    }

    if ($status_codes[$statusCode] !== null) {
        $status_string = $statusCode . ' ' . $status_codes[$statusCode];
        header($_SERVER['SERVER_PROTOCOL'] . ' ' . $status_string, true, $statusCode);
    }
}

You may use it as such:

<?php
header_status(500);

if (that_happened) {
    die("that happened")
}

if (something_else_happened) {
    die("something else happened")
}

update_database();

header_status(200);

This is a short guide on how to send a 500 Internal Server Error header to the client using PHP. This is useful because it allows us to tell the client that the server has encountered an unexpected condition and that it cannot fulfill the request.

Below, I have created a custom PHP function called internal_error.

//Function that sends a 500 Internal Server Error status code to
//the client before killing the script.
function internal_error(){
    header($_SERVER["SERVER_PROTOCOL"] . ' 500 Internal Server Error', true, 500);
    echo '<h1>Something went wrong!</h1>';
    exit;
}

When the PHP function above is called, the script’s execution is halted and “Something went wrong!” is printed out onto the page.

Furthermore, if you inspect the HTTP headers with your browser’s developer console, you will see that the function is returning a 500 Internal Server Error status code:

500 Internal Server Error

Google’s Developer Tools showing the 500 Internal Server Error status that was returned.

To send the 500 status code, we used PHP’s header function like so:

//Send a 500 status code using PHP's header function
header($_SERVER["SERVER_PROTOCOL"] . ' 500 Internal Server Error', true, 500);

Note that we used the SERVER_PROTOCOL variable in this case because the client might be using HTTP 1.0 instead of HTTP 1.1. In other examples, you will find developers making the assumption that the client will always be using HTTP 1.1.

This is not the case.

The problem with PHP is that it doesn’t always send a 500 Internal Server Error when an exception is thrown or a fatal error occurs.

This can cause a number of issues:

  1. It becomes more difficult to handle failed Ajax calls, as the server in question is still responding with a 200 OK status. For example: The JQuery Ajax error handling functions will not be called.
  2. Search engines such as Google may index your error pages. If this happens, your website may lose its rankings.
  3. Other HTTP clients might think that everything is A-OK when it is not.

Note that if you are using PHP version 5.4 or above, you can use the http_response_code function:

//Using http_response_code
http_response_code(500);

Far more concise!

Мне нужно отправить «500 Internal Server Error» из скрипта PHP при определенных условиях. Сценарий должен быть вызван сторонним приложением. Сценарий содержит пару выражений die("this happend") для которых мне нужно отправить код ответа 500 Internal Server Error вместо обычных 200 OK . Третий сторонний скрипт будет повторно отправлять запрос при определенных условиях, которые не включают код ответа 200 OK .

Мне нужно отправить 200 заголовков только после того, как была выполнена последняя строка.

  • Кто добавляет параметр _ _ «Single Underscore Query Parameter?
  • Почему bitmapdata не отправляется на сервер со вспышкой?
  • Как выбрать тип контента из заголовка HTTP Accept в PHP
  • PHP (Apache) безмолвно преобразует HTTP 429 и другие в 500
  • Междоменный AJAX withCredentials, PHP возвращает длину заголовка заголовка, но без содержимого
 header($_SERVER['SERVER_PROTOCOL'] . ' 500 Internal Server Error', true, 500); 

Вы можете использовать следующую функцию для отправки изменения статуса:

 function header_status($statusCode) { static $status_codes = null; if ($status_codes === null) { $status_codes = array ( 100 => 'Continue', 101 => 'Switching Protocols', 102 => 'Processing', 200 => 'OK', 201 => 'Created', 202 => 'Accepted', 203 => 'Non-Authoritative Information', 204 => 'No Content', 205 => 'Reset Content', 206 => 'Partial Content', 207 => 'Multi-Status', 300 => 'Multiple Choices', 301 => 'Moved Permanently', 302 => 'Found', 303 => 'See Other', 304 => 'Not Modified', 305 => 'Use Proxy', 307 => 'Temporary Redirect', 400 => 'Bad Request', 401 => 'Unauthorized', 402 => 'Payment Required', 403 => 'Forbidden', 404 => 'Not Found', 405 => 'Method Not Allowed', 406 => 'Not Acceptable', 407 => 'Proxy Authentication Required', 408 => 'Request Timeout', 409 => 'Conflict', 410 => 'Gone', 411 => 'Length Required', 412 => 'Precondition Failed', 413 => 'Request Entity Too Large', 414 => 'Request-URI Too Long', 415 => 'Unsupported Media Type', 416 => 'Requested Range Not Satisfiable', 417 => 'Expectation Failed', 422 => 'Unprocessable Entity', 423 => 'Locked', 424 => 'Failed Dependency', 426 => 'Upgrade Required', 500 => 'Internal Server Error', 501 => 'Not Implemented', 502 => 'Bad Gateway', 503 => 'Service Unavailable', 504 => 'Gateway Timeout', 505 => 'HTTP Version Not Supported', 506 => 'Variant Also Negotiates', 507 => 'Insufficient Storage', 509 => 'Bandwidth Limit Exceeded', 510 => 'Not Extended' ); } if ($status_codes[$statusCode] !== null) { $status_string = $statusCode . ' ' . $status_codes[$statusCode]; header($_SERVER['SERVER_PROTOCOL'] . ' ' . $status_string, true, $statusCode); } } 

Вы можете использовать его как таковое:

 <?php header_status(500); if (that_happened) { die("that happened") } if (something_else_happened) { die("something else happened") } update_database(); header_status(200); 

PHP 5.4 имеет функцию http_response_code , поэтому, если вы используете PHP 5.4, вы можете просто сделать:

 http_response_code(500); 

Я написал polyfill для этой функции (Gist), если вы используете версию PHP под 5.4.


Чтобы ответить на ваш последующий вопрос, HTTP 1.1 RFC говорит:

Приведенные здесь фразы причины – это только рекомендации – они МОГУТ быть заменены локальными эквивалентами, не затрагивая протокол.

Это означает, что вы можете использовать любой текст, который вы хотите (исключая возврат каретки или линейные каналы) после самого кода, и он будет работать. Как правило, обычно используется лучший код ответа. Например, вместо того, чтобы использовать 500 без записи, вы можете отправить 404 (не найдено), а для чего-то вроде «условия не удались» (я предполагаю ошибку проверки), вы могли бы отправить что-то вроде 422 (непроцессорный организация).

Вы можете просто поставить:

 header("HTTP/1.0 500 Internal Server Error"); 

в ваших условиях:

 if (that happened) { header("HTTP/1.0 500 Internal Server Error"); } 

Что касается запроса к базе данных, вы можете просто сделать это вот так:

 $result = mysql_query("..query string..") or header("HTTP/1.0 500 Internal Server Error"); 

Вы должны помнить, что вы должны поместить этот код перед любым тегом html (или выходом).

Вы можете упростить его так:

 if ( that_happened || something_else_happened ) { header('X-Error-Message: Incorrect username or password', true, 500); die; } 

Он вернет следующий заголовок:

 HTTP/1.1 500 Internal Server Error ... X-Error-Message: Incorrect username or password ... 

Добавлено: Если вам нужно точно знать, что пошло не так, сделайте что-то вроде этого:

 if ( that_happened ) { header('X-Error-Message: Incorrect username', true, 500); die('Incorrect username'); } if ( something_else_happened ) { header('X-Error-Message: Incorrect password', true, 500); die('Incorrect password'); } 

Ваш код должен выглядеть так:

 <?php if ( that_happened ) { header("HTTP/1.0 500 Internal Server Error"); die(); } if ( something_else_happened ) { header("HTTP/1.0 500 Internal Server Error"); die(); } // Your function should return FALSE if something goes wrong if ( !update_database() ) { header("HTTP/1.0 500 Internal Server Error"); die(); } // the script can also fail on the above line // eg a mysql error occurred header('HTTP/1.1 200 OK'); ?> 

Я предполагаю, что вы прекратите выполнение, если что-то пойдет не так.

I just found this question and thought it needs a more comprehensive answer:

As of PHP 5.4 there are three methods to accomplish this:

Assembling the response code on your own (PHP >= 4.0)

The header() function has a special use-case that detects a HTTP response line and lets you replace that with a custom one

header("HTTP/1.1 200 OK");

However, this requires special treatment for (Fast)CGI PHP:

$sapi_type = php_sapi_name();
if (substr($sapi_type, 0, 3) == 'cgi')
    header("Status: 404 Not Found");
else
    header("HTTP/1.1 404 Not Found");

Note: According to the HTTP RFC, the reason phrase can be any custom string (that conforms to the standard), but for the sake of client compatibility I do not recommend putting a random string there.

Note: php_sapi_name() requires PHP 4.0.1

3rd argument to header function (PHP >= 4.3)

There are obviously a few problems when using that first variant. The biggest of which I think is that it is partly parsed by PHP or the web server and poorly documented.

Since 4.3, the header function has a 3rd argument that lets you set the response code somewhat comfortably, but using it requires the first argument to be a non-empty string. Here are two options:

header(':', true, 404);
header('X-PHP-Response-Code: 404', true, 404);

I recommend the 2nd one. The first does work on all browsers I have tested, but some minor browsers or web crawlers may have a problem with a header line that only contains a colon. The header field name in the 2nd. variant is of course not standardized in any way and could be modified, I just chose a hopefully descriptive name.

http_response_code function (PHP >= 5.4)

The http_response_code() function was introduced in PHP 5.4, and it made things a lot easier.

http_response_code(404);

That’s all.

Compatibility

Here is a function that I have cooked up when I needed compatibility below 5.4 but wanted the functionality of the «new» http_response_code function. I believe PHP 4.3 is more than enough backwards compatibility, but you never know…

// For 4.3.0 <= PHP <= 5.4.0
if (!function_exists('http_response_code'))
{
    function http_response_code($newcode = NULL)
    {
        static $code = 200;
        if($newcode !== NULL)
        {
            header('X-PHP-Response-Code: '.$newcode, true, $newcode);
            if(!headers_sent())
                $code = $newcode;
        }       
        return $code;
    }
}

Понравилась статья? Поделить с друзьями:

Интересное по теме:

  • Php ошибка 400
  • Php ошибка 2002
  • Php отследить ошибку
  • Php отправить код ошибки
  • Php отобразить все ошибки

  • Добавить комментарий

    ;-) :| :x :twisted: :smile: :shock: :sad: :roll: :razz: :oops: :o :mrgreen: :lol: :idea: :grin: :evil: :cry: :cool: :arrow: :???: :?: :!: