Sending HTTP response codes from a PHP script is essential for providing proper communication with the client. This article covers three methods for sending custom response codes.
The header() function allows you to define a custom HTTP response line, including the HTTP response code. However, for CGI PHP, you'll need to use the Status HTTP header.
// Assembly manually header("HTTP/1.1 200 OK"); // For CGI PHP if (substr(php_sapi_name(), 0, 3) == 'cgi') header("Status: 404 Not Found"); else header("HTTP/1.1 404 Not Found");
To avoid parsing issues with the manual approach, you can use the third argument of the header() function, which allows you to specify the response code.
// Set the non-empty first argument to anything header(':', true, 404); // Use a custom header field name header('X-PHP-Response-Code: 404', true, 404);
PHP 5.4 introduced the dedicated http_response_code() function, which simplifies the task of setting response codes.
http_response_code(404);
For PHP versions below 5.4, a compatibility function can be used to provide the http_response_code() functionality.
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; }
The above is the detailed content of How to Set Custom HTTP Response Codes in PHP?. For more information, please follow other related articles on the PHP Chinese website!