Home >Backend Development >PHP Tutorial >How Can I Customize HTTP Response Codes in PHP?

How Can I Customize HTTP Response Codes in PHP?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-18 11:01:10409browse

How Can I Customize HTTP Response Codes in PHP?

Customizing HTTP Response Codes in PHP

To tailor HTTP response codes in PHP, employ one of the following approaches:

Manual Construction (PHP 4.0 )

Utilize header() with a custom HTTP response line:

header("HTTP/1.1 200 OK");

However, handle FastCGI PHP differently:

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

Third Argument to Header Function (PHP 4.3 )

Configure response codes comfortably using the third argument:

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

http_response_code Function (PHP 5.4 )

Simplify response code configuration with http_response_code():

http_response_code(404);

Compatibility Function (PHP 4.3 )

For compatibility below PHP 5.4:

if (!function_exists('http_response_code'))
{
    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 Customize HTTP Response Codes 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