Home > Backend Development > PHP Tutorial > How to Send Custom HTTP Response Codes in PHP?

How to Send Custom HTTP Response Codes in PHP?

Patricia Arquette
Release: 2024-12-16 08:36:12
Original
292 people have browsed it

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");
Copy after login

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);
Copy after login

or

header('X-PHP-Response-Code: 404', true, 404);
Copy after login

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);
Copy after login

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)
    {
        // ...
    }
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template