php-generated 503

How to set http response status code and message in php

However, this requires special treatment for (Fast)CGI PHP:,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,since PHP 5.4 you can use http_response_code() for get and set header status code.,The http_response_code() function was introduced in PHP 5.4, and it made things a lot easier.

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:

$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"); 

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); 

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

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.

Answer by Leighton Cantrell

Gets or sets the HTTP response status code. ,http_response_code — Get or Set the HTTP response code, http_​response_​code , The optional response_code will set the response code.

Answer by Ayden Randolph

To return a status code in PHP, the simplest way is to use the http_response_code() function, along with the relevant HTTP status code parameter into your website, followed by the exit() command which stops any more output being set.,As the practice is quite technical, status codes are usually implemented manually by someone who understands coding such as a web developer. However, if your website is on WordPress, then plugins do exist to help you make sense and implement status codes. ,The above gives a brief overview of returning status codes in PHP. However, given the complex nature of coding it’s impossible to cover everything in just one article alone. So we definitely suggest doing some further reading to increase your understanding. ,For example, domain names are actually a series of numerical combinations. Status codes are similar in that they give information about if a page has loaded successfully or not, and the root cause of any errors. PHP is a scripting language that can generate status-code data.

Example: Return a 400 bad request status code

http_response_code(400); exit;

Example: Return a 404 not found status code

http_response_code(404); exit;

This example php code also requires that you provide the new URL, to which the users browser will automatically redirect. For this you need to use the more details header() function.

http_response_code(301); header('Location: /newlocation.html'); exit;

Here’s example code for a 503 temporary error page that also includes additional information that is shown in the browser.

      This is a 503 error page. 
The error is returned in the HTTP header and this is just simple HTML that is displayed in the browser.

Answer by Amaris Rush

Example: This example uses http_response_code() function to send HTTP response code.,For PHP versions 4.0: In order to send the HTTP response code, we need to assemble the response code. To achieve this, use header() function. The header() function contains a special use-case which can detect a HTTP response line and replace that with a custom one.,HTTP Response code: There are three approaches to accomplish the above requirement, depending on the version.,Why to check both isset() and !empty() function in PHP ?

Читайте также:  Change html element with jquery

For PHP versions 4.0: In order to send the HTTP response code, we need to assemble the response code. To achieve this, use header() function. The header() function contains a special use-case which can detect a HTTP response line and replace that with a custom one.

For PHP versions 4.3: There are obviously a few problems when using first method. The biggest one is that it is partly parsed by PHP and is poorly documented. Since the version 4.3, the header() function has an additional 3rd argument through which we can set the response code. but to use the first argument should be a non-empty string.

header(':', true, 400); header(‘X_PHP_Response_Code: 400', true, 400); 

For PHP versions 5.4: This versions uses http_response_code() function to makes things easier.

200 HTTP request successfully

Answer by Aliyah Medina

Any tests and comments are appreciated.,since PHP 5.4 you can use http_response_code() for get and set header status code.,The http_response_code() function was introduced in PHP 5.4, and it made things a lot easier.,There are at least 2 cases when calling http_response_code() result in unexpected behaviour:

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:

$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"); 

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); 

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

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.

You can easily test this bug by calling:

Читайте также:  Java lang illegalargumentexception other has different root

My solution (for all PHP versions since 4.1.0):

$httpStatusCode = 521; $httpStatusMsg = 'Web server is down'; $phpSapiName = substr(php_sapi_name(), 0, 3); if ($phpSapiName == 'cgi' || $phpSapiName == 'fpm') < header('Status: '.$httpStatusCode.' '.$httpStatusMsg); >else < $protocol = isset($_SERVER['SERVER_PROTOCOL']) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.0'; header($protocol.' '.$httpStatusCode.' '.$httpStatusMsg); >

Answer by Coraline Sierra

The optional response_code will set the response code. , Gets or sets the HTTP response status code. ,http_response_code — Get or Set the HTTP response code,Example #1 Using http_response_code() in a web server environment

Answer by Skylar Conway

$url = 'http://www.example.com'; $ch = curl_init($url); curl_setopt($ch, CURLOPT_HEADER, true); // we want headers curl_setopt($ch, CURLOPT_NOBODY, true); // we don't need body curl_setopt($ch, CURLOPT_RETURNTRANSFER,1); curl_setopt($ch, CURLOPT_TIMEOUT,10); $output = curl_exec($ch); $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch); echo 'HTTP code: ' . $httpcode;

Источник

doctor Brain

Для того, чтобы установить определенный код ответа HTTP, в PHP есть встроенная функция http_response_code() .

К счастью для нас, в PHP есть множество встроенных функций, обеспечивающих взаимодействие с веб-интерфейсом. Функция http_response_code() — одна из них, с ее помощью мы можем установить желаемый статус ответа, в том числе: 400, 404, 301, 200, используя всего одну строку кода.

Итак, обратимся к примерам:

Статус 404

http_response_code(404); exit; 

Устанавливает статус ответа 404 Not Found — “не найден” (сервер не может найти запрашиваемый ресурс).

Статус 400

http_response_code(400); exit; 

Устанавливает статус ответа 400 Bad Request — “плохой запрос” (сервер не понимает запрос из-за неверного синтаксиса).

Статус 301

http_response_code(301); exit; 

Устанавливает статус ответа 301 Moved Permanently — “перемещен на постоянной основе” (URI запроса был изменен, новый URI может быть предоставлен в ответе).

Особенности кода

  1. Вызываем функцию http_response_code , передавая в качестве аргумента желаемый статус, как целое число.
  2. Принудительно завершаем скрипт до появления нежелательного поведения, способного привести к смене ответа на “200 ОК”.

Новые публикации

Photo by CHUTTERSNAP on Unsplash

JavaScript: сохраняем страницу в pdf

HTML: Полезные примеры

CSS: Ускоряем загрузку страницы

JavaScript: 5 странностей

JavaScript: конструктор сортировщиков

Категории

О нас

Frontend & Backend. Статьи, обзоры, заметки, код, уроки.

© 2021 dr.Brain .
мир глазами веб-разработчика

Источник

henriquemoody / http-status-codes.php

This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters

/**
* Content from http://en.wikipedia.org/wiki/List_of_HTTP_status_codes
*
* You may also want a list of unofficial codes:
*
* 103 => ‘Checkpoint’,
* 218 => ‘This is fine’, // Apache Web Server
* 419 => ‘Page Expired’, // Laravel Framework
* 420 => ‘Method Failure’, // Spring Framework
* 420 => ‘Enhance Your Calm’, // Twitter
* 430 => ‘Request Header Fields Too Large’, // Shopify
* 450 => ‘Blocked by Windows Parental Controls’, // Microsoft
* 498 => ‘Invalid Token’, // Esri
* 499 => ‘Token Required’, // Esri
* 509 => ‘Bandwidth Limit Exceeded’, // Apache Web Server/cPanel
* 526 => ‘Invalid SSL Certificate’, // Cloudflare and Cloud Foundry’s gorouter
* 529 => ‘Site is overloaded’, // Qualys in the SSLLabs
* 530 => ‘Site is frozen’, // Pantheon web platform
* 598 => ‘Network read timeout error’, // Informal convention
* 440 => ‘Login Time-out’, // IIS
* 449 => ‘Retry With’, // IIS
* 451 => ‘Redirect’, // IIS
* 444 => ‘No Response’, // nginx
* 494 => ‘Request header too large’, // nginx
* 495 => ‘SSL Certificate Error’, // nginx
* 496 => ‘SSL Certificate Required’, // nginx
* 497 => ‘HTTP Request Sent to HTTPS Port’, // nginx
* 499 => ‘Client Closed Request’, // nginx
* 520 => ‘Web Server Returned an Unknown Error’, // Cloudflare
* 521 => ‘Web Server Is Down’, // Cloudflare
* 522 => ‘Connection Timed Out’, // Cloudflare
* 523 => ‘Origin Is Unreachable’, // Cloudflare
* 524 => ‘A Timeout Occurred’, // Cloudflare
* 525 => ‘SSL Handshake Failed’, // Cloudflare
* 526 => ‘Invalid SSL Certificate’, // Cloudflare
* 527 => ‘Railgun Error’, // Cloudflare
*/
return [
100 => ‘Continue’ ,
101 => ‘Switching Protocols’ ,
102 => ‘Processing’ , // WebDAV; RFC 2518
103 => ‘Early Hints’ , // RFC 8297
200 => ‘OK’ ,
201 => ‘Created’ ,
202 => ‘Accepted’ ,
203 => ‘Non-Authoritative Information’ , // since HTTP/1.1
204 => ‘No Content’ ,
205 => ‘Reset Content’ ,
206 => ‘Partial Content’ , // RFC 7233
207 => ‘Multi-Status’ , // WebDAV; RFC 4918
208 => ‘Already Reported’ , // WebDAV; RFC 5842
226 => ‘IM Used’ , // RFC 3229
300 => ‘Multiple Choices’ ,
301 => ‘Moved Permanently’ ,
302 => ‘Found’ , // Previously «Moved temporarily»
303 => ‘See Other’ , // since HTTP/1.1
304 => ‘Not Modified’ , // RFC 7232
305 => ‘Use Proxy’ , // since HTTP/1.1
306 => ‘Switch Proxy’ ,
307 => ‘Temporary Redirect’ , // since HTTP/1.1
308 => ‘Permanent Redirect’ , // RFC 7538
400 => ‘Bad Request’ ,
401 => ‘Unauthorized’ , // RFC 7235
402 => ‘Payment Required’ ,
403 => ‘Forbidden’ ,
404 => ‘Not Found’ ,
405 => ‘Method Not Allowed’ ,
406 => ‘Not Acceptable’ ,
407 => ‘Proxy Authentication Required’ , // RFC 7235
408 => ‘Request Timeout’ ,
409 => ‘Conflict’ ,
410 => ‘Gone’ ,
411 => ‘Length Required’ ,
412 => ‘Precondition Failed’ , // RFC 7232
413 => ‘Payload Too Large’ , // RFC 7231
414 => ‘URI Too Long’ , // RFC 7231
415 => ‘Unsupported Media Type’ , // RFC 7231
416 => ‘Range Not Satisfiable’ , // RFC 7233
417 => ‘Expectation Failed’ ,
418 => ‘I\’m a teapot’ , // RFC 2324, RFC 7168
421 => ‘Misdirected Request’ , // RFC 7540
422 => ‘Unprocessable Entity’ , // WebDAV; RFC 4918
423 => ‘Locked’ , // WebDAV; RFC 4918
424 => ‘Failed Dependency’ , // WebDAV; RFC 4918
425 => ‘Too Early’ , // RFC 8470
426 => ‘Upgrade Required’ ,
428 => ‘Precondition Required’ , // RFC 6585
429 => ‘Too Many Requests’ , // RFC 6585
431 => ‘Request Header Fields Too Large’ , // RFC 6585
451 => ‘Unavailable For Legal Reasons’ , // RFC 7725
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’ , // RFC 2295
507 => ‘Insufficient Storage’ , // WebDAV; RFC 4918
508 => ‘Loop Detected’ , // WebDAV; RFC 5842
510 => ‘Not Extended’ , // RFC 2774
511 => ‘Network Authentication Required’ , // RFC 6585
];

Источник

Оцените статью