php вернуть код 200
PHP: как отправить код ответа HTTP?
У меня есть php-скрипт, который должен делать ответы с кодами ответов HTTP (коды состояния), например HTTP 200 OK, или какой-то код 4XX или 5XX.
Как я могу это сделать в PHP?
7 ответов
Я только что нашел этот вопрос и подумал, что ему нужен более полный ответ:
по состоянию на PHP 5.4 есть три способа достижения этого:
сборка кода ответа самостоятельно (PHP >= 4.0)
на header() функция имеет специальный прецедент, который обнаруживает строку ответа HTTP и позволяет заменить ее пользовательской
однако, это требует специального лечения (Быстро)CGI PHP:
Примечание: по словам HTTP RFC на почему фраза может быть любой пользовательской строкой (которая соответствует стандарту), но ради совместимости с клиентом I не рекомендуем поместить туда случайную строку.
Примечание: php_sapi_name() требует PHP 4.0.1
3-й аргумент функции заголовка (PHP >= 4.3)
очевидно, есть несколько проблем при использовании этого первого варианта. Самый большой из которых я думаю, что он частично проанализирован PHP или веб-сервером и плохо документирован.
начиная с 4.3, то header функция имеет 3-й аргумент, который позволяет вам установить код ответа несколько удобно, но использование его требует, чтобы первый аргумент был непустой строкой. Вот два варианта:
я рекомендую 2-й. Первый тут работа во всех браузерах, которые я тестировал, но некоторые второстепенные браузеры или веб-искатели могут иметь проблемы со строкой заголовка, которая содержит только двоеточие. Имя поля заголовка во 2-ом. вариант, конечно, никоим образом не стандартизирован и может быть изменен, я просто выбрал, надеюсь, описательное имя.
функция http_response_code (PHP >= 5.4)
на http_response_code() функция была введена в PHP 5.4, и это сделало вещи a лот!—14—> легче.
совместимость
вот функция, которую я приготовил, когда мне нужна совместимость ниже 5.4, но хотел функциональность «нового»
к сожалению, я нашел решения, представленные @dualed имеют различные недостатки.
используя substr($sapi_type, 0, 3) == ‘cgi’ не enogh для обнаружения быстрого CGI. При использовании PHP-FPM FastCGI Process Manager, php_sapi_name() возвращает fpm не cgi
Fasctcgi и php-fpm разоблачают еще одну ошибку, упомянутую @Josh-using header(‘X-PHP-Response-Code: 404’, true, 404); работает правильно под PHP-FPM (FastCGI)
есть по крайней мере 2 случая, когда вызов http_response_code() результат неожиданного поведения:
для вашей справки здесь полный список кодов состояния ответа HTTP (это список включает коды из интернет-стандартов IETF, а также других Рчк IETF. Многие из них в настоящее время не поддерживаются функцией PHP http_response_code):http://en.wikipedia.org/wiki/List_of_HTTP_status_codes
вы можете легко проверить эту ошибку, позвонив:
сервер отправит код ответа HTTP» 500 внутренних ошибок сервера», что приведет к непредвиденным ошибкам, если у вас есть, например, пользовательское клиентское приложение, вызывающее ваш сервер и ожидающее некоторые дополнительные коды HTTP.
мое решение (для всех версий PHP, начиная с 4.1.0):
вывод
реализация http_response_code () не поддерживает все коды ответа HTTP и может перезаписать указанный код ответа HTTP с другим из той же группы.
новая функция http_response_code() не решает все проблемы, но делает вещи хуже представляем новые ошибки.
решение «совместимость», предлагаемое @dualed, работает не так, как ожидалось, по крайней мере, в PHP-FPM.
другие решения, предлагаемые @dualed также имеют различные ошибки. Быстрое обнаружение CGI не обрабатывает PHP-FPM. Настоящий протокол должен быть обнаружен.
любые тесты и комментарии.
добавьте следующую строку перед любым выходом из тела, в случае, если вы не используете буферизацию вывода.
замените часть сообщения (‘OK’) соответствующим сообщением, а код состояния-соответствующим кодом (404, 501 и т. д.)
начиная с PHP 5.4 вы можете использовать http_response_code() для get и set код состояния заголовка.
PHP: How to send HTTP response code?
I have a PHP script that needs to make responses with HTTP response codes (status-codes), like HTTP 200 OK, or some 4XX or 5XX code.
How can I do this in PHP?
8 Answers 8
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
However, this requires special treatment for (Fast)CGI PHP:
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:
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.
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.
Unfortunately I found solutions presented by @dualed have various flaws.
Using substr($sapi_type, 0, 3) == ‘cgi’ is not enogh to detect fast CGI. When using PHP-FPM FastCGI Process Manager, php_sapi_name() returns fpm not cgi
There are at least 2 cases when calling http_response_code() result in unexpected behaviour:
For your reference here there is the full list of HTTP response status codes (this list includes codes from IETF internet standards as well as other IETF RFCs. Many of them are NOT currently supported by PHP http_response_code function): http://en.wikipedia.org/wiki/List_of_HTTP_status_codes
You can easily test this bug by calling:
The server will send «500 Internal Server Error» HTTP response code resulting in unexpected errors if you have for example a custom client application calling your server and expecting some additional HTTP codes.
My solution (for all PHP versions since 4.1.0):
Conclusion
http_response_code() implementation does not support all HTTP response codes and may overwrite the specified HTTP response code with another one from the same group.
The new http_response_code() function does not solve all the problems involved but make things worst introducing new bugs.
The «compatibility» solution offered by @dualed does not work as expected, at least under PHP-FPM.
The other solutions offered by @dualed also have various bugs. Fast CGI detection does not handle PHP-FPM. Current protocol must be detected.
http_response_code
(PHP 5 >= 5.4.0, PHP 7, PHP 8)
http_response_code — Получает или устанавливает код ответа HTTP
Описание
Получает или задаёт коды ответов HTTP.
Список параметров
Возвращаемые значения
Примеры
Пример #1 Использование http_response_code() в окружении веб-сервера
// Берём текущий код и устанавливаем новый
var_dump ( http_response_code ( 404 ));
// Берём новый код
var_dump ( http_response_code ());
?>
Результат выполнения данного примера:
Пример #2 Использование http_response_code() в CLI
// Берём текущий код по умолчанию
var_dump ( http_response_code ());
// Устанавливаем код
var_dump ( http_response_code ( 201 ));
// Берём новый код
var_dump ( http_response_code ());
?>
Результат выполнения данного примера:
Смотрите также
User Contributed Notes 18 notes
If your version of PHP does not include this function:
For reference the error codes I got from PHP’s source code:
And how the current http header is sent, with the variables it uses:
Note that you can NOT set arbitrary response codes with this function, only those that are known to PHP (or the SAPI PHP is running on).
The following codes currently work as expected (with PHP running as Apache module):
200 – 208, 226
300 – 305, 307, 308
400 – 417, 422 – 424, 426, 428 – 429, 431
500 – 508, 510 – 511
Codes 0, 100, 101, and 102 will be sent as «200 OK».
Everything else will result in «500 Internal Server Error».
If you want to send responses with a freestyle status line, you need to use the `header()` function:
When setting the response code to non-standard ones like 420, Apache outputs 500 Internal Server Error.
This happens when using header(0,0,420) and http_response_code(420).
Use header(‘HTTP/1.1 420 Enhance Your Calm’) instead.
Note that the response code in the string IS interpreted and used in the access log and output via http_response_code().
Status codes as an array:
You can also create a enum by extending the SplEnum class.
/** HTTP status codes */
class HttpStatusCode extends SplEnum <
const __default = self :: OK ;
const SWITCHING_PROTOCOLS = 101 ;
const OK = 200 ;
const CREATED = 201 ;
const ACCEPTED = 202 ;
const NONAUTHORITATIVE_INFORMATION = 203 ;
const NO_CONTENT = 204 ;
const RESET_CONTENT = 205 ;
const PARTIAL_CONTENT = 206 ;
const MULTIPLE_CHOICES = 300 ;
const MOVED_PERMANENTLY = 301 ;
const MOVED_TEMPORARILY = 302 ;
const SEE_OTHER = 303 ;
const NOT_MODIFIED = 304 ;
const USE_PROXY = 305 ;
const BAD_REQUEST = 400 ;
const UNAUTHORIZED = 401 ;
const PAYMENT_REQUIRED = 402 ;
const FORBIDDEN = 403 ;
const NOT_FOUND = 404 ;
const METHOD_NOT_ALLOWED = 405 ;
const NOT_ACCEPTABLE = 406 ;
const PROXY_AUTHENTICATION_REQUIRED = 407 ;
const REQUEST_TIMEOUT = 408 ;
const CONFLICT = 408 ;
const GONE = 410 ;
const LENGTH_REQUIRED = 411 ;
const PRECONDITION_FAILED = 412 ;
const REQUEST_ENTITY_TOO_LARGE = 413 ;
const REQUESTURI_TOO_LARGE = 414 ;
const UNSUPPORTED_MEDIA_TYPE = 415 ;
const REQUESTED_RANGE_NOT_SATISFIABLE = 416 ;
const EXPECTATION_FAILED = 417 ;
const IM_A_TEAPOT = 418 ;
const INTERNAL_SERVER_ERROR = 500 ;
const NOT_IMPLEMENTED = 501 ;
const BAD_GATEWAY = 502 ;
const SERVICE_UNAVAILABLE = 503 ;
const GATEWAY_TIMEOUT = 504 ;
const HTTP_VERSION_NOT_SUPPORTED = 505 ;
>
Do not mix the use of http_response_code() and manually setting the response code header because the actual HTTP status code being returned by the web server may not end up as expected. http_response_code() does not work if the response code has previously been set using the header() function. Example:
( ‘HTTP/1.1 401 Unauthorized’ );
http_response_code ( 403 );
print( http_response_code ());
?>
The raw HTTP response will be (notice the actual status code on the first line does not match the printed http_response_code in the body):
HTTP/1.1 401 Unauthorized
Date: Tue, 24 Nov 2020 13:49:08 GMT
Server: Apache
Connection: Upgrade, Keep-Alive
Keep-Alive: timeout=5, max=100
Transfer-Encoding: chunked
Content-Type: text/html; charset=UTF-8
I only tested it on Apache. I am not sure if this behavior is specific to Apache or common to all PHP distributions.
The note above from «Anonymous» is wrong. I’m running this behind the AWS Elastic Loadbalancer and trying the header(‘:’.$error_code. ) method mentioned above is treated as invalid HTTP.
The documentation for the header() function has the right way to implement this if you’re still on ( «HTTP/1.0 404 Not Found» );
?>
At least on my side with php-fpm and nginx this method does not change the text in the response, only the code.
// HTTP/1.1 404 Not Found
http_response_code ( 404 );
?>
The resulting response is HTTP/1.1 404 OK
http_response_code() does not actually send HTTP headers, it only prepares the header list to be sent later on.
So you can call http_reponse_code() to set, get and reset the HTTP response code before it gets sent.
http_response_code(500); // set the code
var_dump(headers_sent()); // check if headers are sent
http_response_code(200); // avoid a default browser page
http_response_code is basically a shorthand way of writing a http status header, with the added bonus that PHP will work out a suitable Reason Phrase to provide by matching your response code to one of the values in an enumeration it maintains within php-src/main/http_status_codes.h. Note that this means your response code must match a response code that PHP knows about. You can’t create your own response codes using this method, however you can using the header method.
1. Using http_response_code will cause PHP to match and apply a Reason Phrase from a list of Reason Phrases that are hard-coded into the PHP source code.
2. Because of point 1 above, if you use http_response_code you must set a code that PHP knows about. You can’t set your own custom code, however you can set a custom code (and Reason Phrase) if you use the header method.
It’s not mentioned explicitly, but the return value when SETTING, is the OLD status code.
e.g.
= http_response_code ();
$b = http_response_code ( 202 );
$c = http_response_code ();