- How to set http response status code and message in php
- Answer by Leighton Cantrell
- Answer by Ayden Randolph
- Example: Return a 400 bad request status code
- Example: Return a 404 not found status code
- Answer by Amaris Rush
- Answer by Aliyah Medina
- Answer by Coraline Sierra
- Answer by Skylar Conway
- Мой путь в мире web-devel
- Мой путь в мире web-devel
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 ?
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:
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;
Мой путь в мире web-devel
Начинающие веб-разработчики (в том числе и я) не понимают основную функцию веб-приложения (не только php). А ведь это очень важно и в то же время очень просто. Основная функция веб-приложения получить запрос от клиента, подготовить ответ (здесь выполняются различные действия получения данных и их обработки), вернуть ответ клиенту.
Очень часто запрос и ответ реализуются в веб-приложениях в виде классов Request и Response. Тогда все что нужно будет приложению это определить путь запроса Request и вернуть соответствующий пути ответ Response. UML-диаграмма классов Request и Response представлена ниже:
Как мы видим в классе Request есть три метода:
- getPathInfo() — метод получения пути запроса
- find(key) — поиск параметра запроса по ключу key
- has(key) — проверка существования параметра в запроса
- Response(content, status_code, headers) — конструктор класса, принимает в качестве параметров один обязательный содержимое ответа и два не обязательных status_code (200 — по умолчанию), headers — массив HTTP-заголовков
- setStatusCode(status_code) — из названия понятно что этот метод делает
- setHeader(header) — то же
- send() — отправка ответа на вывод
- content — содержимое ответа
- status_code — код ответа
- headers — массив, содержащий HTTP-заголовки ответа
/** * Поиск и получение значения параметра зпроса * по ключу * * @param string $key искомый ключ параметра запроса * @return mixed значение параметра * или null если параметр не существует */ public function find($key) < if ( key_exists($key, $_REQUEST) ) return $_REQUEST[$key]; else return null; >/** * Проверяет существование параметра в запросе * по его ключу * * @param string $key проверяемый ключ * @return boolean */ public function has($key) < return key_exists($key, $_REQUEST); >> ?>
content = $content; $this->status_code = $status_code; $this->headers = $headers; > public function setStatusCode($status_code) < $this->status_code = $status_code; > public function setHeader($header) < $this->headers[] = $header; > public function send() < // выслать код статуса HTTP header('HTTP/1.1 ' . $this->status_code); // отправить заголовки HTTP foreach ( $this->headers as $header ) header($header); // отправить содержимое ответа echo $this->content; > > ?>
Пример использования этих классов index.php:
getPathInfo(); // создаем ответ в соответствии с путем запроса if ( $path_info == '/' ) $response = new Response('Main page'); else if ( $path_info == 'contact') $response = new Response('Contact page'); else $response = new Response('Not found 404', 404); // возвращаем ответ клиенту $response->send(); ?>
Мой путь в мире web-devel
Начинающие веб-разработчики (в том числе и я) не понимают основную функцию веб-приложения (не только php). А ведь это очень важно и в то же время очень просто. Основная функция веб-приложения получить запрос от клиента, подготовить ответ (здесь выполняются различные действия получения данных и их обработки), вернуть ответ клиенту.
Очень часто запрос и ответ реализуются в веб-приложениях в виде классов Request и Response. Тогда все что нужно будет приложению это определить путь запроса Request и вернуть соответствующий пути ответ Response. UML-диаграмма классов Request и Response представлена ниже:
Как мы видим в классе Request есть три метода:
- getPathInfo() — метод получения пути запроса
- find(key) — поиск параметра запроса по ключу key
- has(key) — проверка существования параметра в запроса
- Response(content, status_code, headers) — конструктор класса, принимает в качестве параметров один обязательный содержимое ответа и два не обязательных status_code (200 — по умолчанию), headers — массив HTTP-заголовков
- setStatusCode(status_code) — из названия понятно что этот метод делает
- setHeader(header) — то же
- send() — отправка ответа на вывод
- content — содержимое ответа
- status_code — код ответа
- headers — массив, содержащий HTTP-заголовки ответа
/** * Поиск и получение значения параметра зпроса * по ключу * * @param string $key искомый ключ параметра запроса * @return mixed значение параметра * или null если параметр не существует */ public function find($key) < if ( key_exists($key, $_REQUEST) ) return $_REQUEST[$key]; else return null; >/** * Проверяет существование параметра в запросе * по его ключу * * @param string $key проверяемый ключ * @return boolean */ public function has($key) < return key_exists($key, $_REQUEST); >> ?>
content = $content; $this->status_code = $status_code; $this->headers = $headers; > public function setStatusCode($status_code) < $this->status_code = $status_code; > public function setHeader($header) < $this->headers[] = $header; > public function send() < // выслать код статуса HTTP header('HTTP/1.1 ' . $this->status_code); // отправить заголовки HTTP foreach ( $this->headers as $header ) header($header); // отправить содержимое ответа echo $this->content; > > ?>
Пример использования этих классов index.php:
getPathInfo(); // создаем ответ в соответствии с путем запроса if ( $path_info == '/' ) $response = new Response('Main page'); else if ( $path_info == 'contact') $response = new Response('Contact page'); else $response = new Response('Not found 404', 404); // возвращаем ответ клиенту $response->send(); ?>