Home > Backend Development > PHP Tutorial > How Can I Send Custom HTTP Status Messages in PHP?

How Can I Send Custom HTTP Status Messages in PHP?

Susan Sarandon
Release: 2024-12-29 18:40:10
Original
170 people have browsed it

How Can I Send Custom HTTP Status Messages in PHP?

PHP Response Codes: How to Send Custom HTTP Status Messages

Introduction

In web applications, it's often necessary to communicate specific results or error messages to clients. HTTP response codes allow us to convey this information using standardized numerical codes, such as HTTP 200 OK or 404 Not Found. PHP provides several methods for sending custom HTTP response codes.

Method 1: Assembling the Response Line (PHP >= 4.0)

The header() function allows you to set custom HTTP response lines, including the status code. However, special handling is required for (Fast)CGI PHP.

header("HTTP/1.1 200 OK");
Copy after login

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

Method 2: 3rd Argument to header Function (PHP >= 4.3)

With PHP 4.3 and later, the header() function can set the response code in the third argument. However, a non-empty first argument is required. Two options are:

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

Method 3: http_response_code Function (PHP >= 5.4)

PHP 5.4 introduced the http_response_code() function, which simplifies the process:

http_response_code(404);
Copy after login

Compatibility

Below PHP 5.4, you can use the following compatibility function:

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

The above is the detailed content of How Can I Send Custom HTTP Status Messages 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