PHP 响应代码:如何发送自定义 HTTP 状态消息
简介
网络中在应用程序中,通常需要向客户端传达特定的结果或错误消息。 HTTP 响应代码允许我们使用标准化数字代码来传达此信息,例如 HTTP 200 OK 或 404 Not Found。 PHP 提供了多种发送自定义 HTTP 响应代码的方法。
方法 1:组装响应行 (PHP >= 4.0)
header() 函数允许您设置自定义 HTTP 响应行,包括状态代码。但是,(快速)CGI PHP 需要特殊处理。
header("HTTP/1.1 200 OK");
对于(快速)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");
方法 2:标头函数的第三个参数 ( PHP >= 4.3)
使用 PHP 4.3 及更高版本, header() 函数可以在第三个参数中设置响应代码。但是,第一个参数必须非空。两个选项是:
header(':', true, 404); header('X-PHP-Response-Code: 404', true, 404);
方法 3:http_response_code 函数 (PHP >= 5.4)
PHP 5.4 引入了 http_response_code() 函数,它简化了流程:
http_response_code(404);
兼容性
PHP 5.4以下,可以使用以下兼容性函数:
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; }
以上是如何在 PHP 中发送自定义 HTTP 状态消息?的详细内容。更多信息请关注PHP中文网其他相关文章!