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

How to Set Custom HTTP Response Codes in PHP?

Barbara Streisand
Release: 2024-12-15 12:18:09
Original
150 people have browsed it

How to Set Custom HTTP Response Codes in PHP?

How to Send an HTTP Response Code in PHP

Sending HTTP response codes from a PHP script is essential for providing proper communication with the client. This article covers three methods for sending custom response codes.

PHP 4.0 : Manual Response Code Assembly

The header() function allows you to define a custom HTTP response line, including the HTTP response code. However, for CGI PHP, you'll need to use the Status HTTP header.

// Assembly manually
header("HTTP/1.1 200 OK");

// For CGI PHP
if (substr(php_sapi_name(), 0, 3) == 'cgi')
    header("Status: 404 Not Found");
else
    header("HTTP/1.1 404 Not Found");
Copy after login

PHP 4.3 : Header Function's Third Argument

To avoid parsing issues with the manual approach, you can use the third argument of the header() function, which allows you to specify the response code.

// Set the non-empty first argument to anything
header(':', true, 404);

// Use a custom header field name
header('X-PHP-Response-Code: 404', true, 404);
Copy after login

PHP 5.4 : http_response_code() Function

PHP 5.4 introduced the dedicated http_response_code() function, which simplifies the task of setting response codes.

http_response_code(404);
Copy after login

Compatibility Function for PHP 4.3

For PHP versions below 5.4, a compatibility function can be used to provide the http_response_code() functionality.

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 to Set 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