To tailor HTTP response codes in PHP, employ one of the following approaches:
Utilize header() with a custom HTTP response line:
header("HTTP/1.1 200 OK");
However, handle FastCGI PHP differently:
$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");
Configure response codes comfortably using the third argument:
header(':', true, 404); header('X-PHP-Response-Code: 404', true, 404);
Simplify response code configuration with http_response_code():
http_response_code(404);
For compatibility below PHP 5.4:
if (!function_exists('http_response_code')) { 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 Can I Customize HTTP Response Codes in PHP?. For more information, please follow other related articles on the PHP Chinese website!