Home >Backend Development >PHP Tutorial >How to Send Custom HTTP Response Codes in PHP?
How to Send HTTP Response Codes with PHP
Introduction:
When developing web applications, it's essential to be able to send custom HTTP response codes to the client. These codes convey the status of the request and provide valuable information to browsers and other clients.
Methods for Sending HTTP Response Codes:
PHP provides several methods for sending HTTP response codes:
1. Assembling Response Code Manually (PHP >= 4.0):
Using the header() function with a specific format:
header("HTTP/1.1 200 OK");
Note that you'll need to handle special cases for (Fast)CGI environments.
2. Using the 3rd Argument to the header() Function (PHP >= 4.3):
Providing the response code as the third argument:
header(':', true, 404);
or
header('X-PHP-Response-Code: 404', true, 404);
3. Using the http_response_code() Function (PHP >= 5.4):
This function provides a straightforward way to set the HTTP response code:
http_response_code(404);
Compatibility:
For backward compatibility with PHP versions below 5.4, you can use the following compatibility function:
if (!function_exists('http_response_code')) { function http_response_code($newcode = NULL) { // ... } }
Conclusion:
By utilizing these methods, PHP developers can easily send HTTP response codes to the client, providing more control over the handling of requests and enhancing the user experience.
The above is the detailed content of How to Send Custom HTTP Response Codes in PHP?. For more information, please follow other related articles on the PHP Chinese website!