- How to send a status code in PHP, without maintaining an array of status names?
- 5 Answers 5
- send response HTTP 200 SUCCESS in php
- PHP: How to send HTTP response code?
- 7 Answers 7
- Assembling the response code on your own (PHP >= 4.0)
- 3rd argument to header function (PHP >= 4.3)
- http_response_code function (PHP >= 5.4)
- Compatibility
How to send a status code in PHP, without maintaining an array of status names?
All I want to do, is send a 404 status code from PHP — but in a generic fashion. Both Router::statusCode(404) and Router::statusCode(403) should work, as well as any other valid HTTP status code. I do know, that you can specify a status code as third parameter to header . Sadly this only works if you specify a string . Thus calling header(», false, 404) does not work. Furthermore I know, that one can send a status code via a header call with a status line: header(‘HTTP/1.1 404 Not Found’) But to do this I have to maintain an array of reason phrases ( Not Found ) for all status codes ( 404 ). I don’t like the idea of this, as it somehow is a duplication of what PHP already does itself (for the third header parameter). So, my question is: Is there any simple and clean way to send a status code in PHP?
The simple and clean way is to send the proper header. Any other way (including using the 3rd parameter to header() IMHO) is dirty. There are not that many status codes, and they are well documented. What’s not clean about doing a simple map?
5 Answers 5
There is a new function for this in PHP >= 5.4.0 http_response_code
Simply do http_response_code(404) .
If you have a lower PHP version try header(‘ ‘, true, 404); (note the whitespace in the string).
If you want to set the reason phrase as well try:
header('HTTP/ 433 Reason Phrase As You Wish');
+1 for the whitespace at the beginning. The second parameter can be either true or false according to my experience.
It doesn’t matter. The result is the same if the second parameter is set to true or false. In fact, it can be marginally faster with it set to false because php doesn’t try to replace previous headers.
The actual text of the code is irrelevant. You could do
header('The goggles, they do nawtink!', true, 404);
and it’d still be seen as a 404 by the browser — it’s the code that matters.
No, just a goofy way to show that the text of the header is irrelevant, as long as the status code is there.
+1 because it’s true, and because a comment like that is certainly going to make that apparent to any future developers 🙂 @ircmaxell — hey, it’s php!
Sure, not saying to put something totally different, like «Access denied» for a 404, but «Not found» is just a simple suggested default. You could put a 500 page poem that boils down to the same thing if you so chose.
Zend Framework has a packaged solution in Zend_Http_Response
/** * List of all known HTTP response codes - used by responseCodeAsText() to * translate numeric codes to messages. * * @var array */ protected static $messages = array( // Informational 1xx 100 => 'Continue', 101 => 'Switching Protocols', // Success 2xx 200 => 'OK', 201 => 'Created', 202 => 'Accepted', 203 => 'Non-Authoritative Information', 204 => 'No Content', 205 => 'Reset Content', 206 => 'Partial Content', // Redirection 3xx 300 => 'Multiple Choices', 301 => 'Moved Permanently', 302 => 'Found', // 1.1 303 => 'See Other', 304 => 'Not Modified', 305 => 'Use Proxy', // 306 is deprecated but reserved 307 => 'Temporary Redirect', // Client Error 4xx 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', // Server Error 5xx 500 => 'Internal Server Error', 501 => 'Not Implemented', 502 => 'Bad Gateway', 503 => 'Service Unavailable', 504 => 'Gateway Timeout', 505 => 'HTTP Version Not Supported', 509 => 'Bandwidth Limit Exceeded' );
Even if you’re not using zend-framework you might be able to break this out for personal use.
send response HTTP 200 SUCCESS in php
I need to send an HTTP 200 response to the string ‘SUCCESS’, but my php server version is 5.2.17! In my case, the webhook sends data to the capture to a file called notification.php, I read the contentes, save in the database and need to send a response but do not know how to do this! Does anyone know how to do this in php 5.2.17? I tried the following ways without success:
// error 1 header("Content-Type: text/plain"); echo "SUCCESS"; // error 2 $httpStatusCode = 200; $httpStatusMsg = 'SUCCESS'; $protocol = isset($_SERVER['SERVER_PROTOCOL']) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.0'; header($protocol.' '.$httpStatusCode.' '.$httpStatusMsg); // error 3 header("200 SUCCESS"); return "200 SUCCESS"; // error 4 header('Content-Type: application/json'); echo 'SUCCESS'; // error 5 header('Content-Type: application/json'); return 'SUCCESS'; //error 6 header('Content-Type: application/json'); header('SUCCESS'); ///error 7 header('Content-Type: application/json'); $success =json_encode('SUCCESS'); header($success); ///error 8 header("HTTP/1.1 200 SUCCESS"); header("Content-Type:application/json; charset=utf-8"); ///error 9 header("HTTP/1.1 200"); header("Content-Type:application/json; charset=utf-8"); result 'SUCCESS'; //error 10 header("Content-Type:application/json;"); header('HTTP/1.0 200 SUCCESS'); // error 11 $code = 200; $text = 'OK'; $protocol = (isset($_SERVER['SERVER_PROTOCOL']) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.0'); header($protocol . ' ' . $code . ' ' . $text); $GLOBALS['http_response_code'] = $code; echo 'SUCCESS';
payment->id; $id_cus = $data->payment->customer; $status = $data->payment->status; $dtsts = date("Y-m-d"); if ($data->event == 'PAYMENT_RECEIVED') < // post client include('dbconnection.php'); $qryn = "UPDATE PAYMENTS SET STATUS='$status', DATASTATUS='$dtsts' WHERE ID_COB_ASAAS='$id_cob' AND ID_CLI_ASAAS='$id_cus'"; mysql_query($qryn,$cnx); >// webhook return // my solution was: header('HTTP/1.1 200 OK'); echo 'SUCCESS'; return; ?>
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?
None of the answers say what to do after calling header() for a 404 error detected in PHP code. Is exit() okay?
7 Answers 7
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:
$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.
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.