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

How to Set HTTP Response Codes in PHP?

Patricia Arquette
Release: 2024-12-16 09:51:11
Original
252 people have browsed it

How to Set HTTP Response Codes in PHP?

HTTP Response Codes in PHP

Introduction

Handling HTTP response codes in PHP is essential for sending appropriate HTTP status messages to clients. This article explores three methods to set HTTP response codes in PHP, depending on the PHP version and requirements.

Methods to Set HTTP Response Codes

1. Assembling the Response Code (PHP >= 4.0)

The header() function can be used to set custom HTTP response lines. While this method has special use cases, it requires careful consideration for FastCGI PHP.

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

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

The header() function provides a third argument for setting the response code. However, the first argument must be a non-empty string. This method offers two options:

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

3. http_response_code Function (PHP >= 5.4)

Introduced in PHP 5.4, the http_response_code() function simplifies the process of setting HTTP response codes.

http_response_code(404);
Copy after login

Compatibility

For PHP versions below 5.4, a custom function can provide compatibility with the http_response_code() functionality:

// For 4.3.0 <= PHP <= 5.4.0
if (!function_exists('http_response_code')) {
    function http_response_code($newcode = NULL) {
        // ...
    }
}
Copy after login

The above is the detailed content of How to Set 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