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
Susan SarandonOriginal
2024-12-29 18:40:10179browse

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");

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");

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);

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);

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;
}

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!

Statement:
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
Previous article:Prunable Eloquent ModelsNext article:Prunable Eloquent Models