Home >Backend Development >PHP Tutorial >How to Set HTTP Response Codes in PHP?
Handling HTTP response codes in PHP is essential for sending appropriate HTTP status messages to clients. This article explores three methods to set HTTP response codes in PHP, depending on the PHP version and requirements.
The header() function can be used to set custom HTTP response lines. While this method has special use cases, it requires careful consideration for FastCGI PHP.
header("HTTP/1.1 200 OK");
The header() function provides a third argument for setting the response code. However, the first argument must be a non-empty string. This method offers two options:
header(':', true, 404); header('X-PHP-Response-Code: 404', true, 404); // Recommended
Introduced in PHP 5.4, the http_response_code() function simplifies the process of setting HTTP response codes.
http_response_code(404);
For PHP versions below 5.4, a custom function can provide compatibility with the http_response_code() functionality:
// For 4.3.0 <= PHP <= 5.4.0 if (!function_exists('http_response_code')) { function http_response_code($newcode = NULL) { // ... } }
The above is the detailed content of How to Set HTTP Response Codes in PHP?. For more information, please follow other related articles on the PHP Chinese website!