How to Retrieve HTTP Response Headers in PHP Using get_headers()

This guide explains the PHP get_headers() function, its syntax, parameters, and usage examples, showing how to fetch and inspect HTTP response headers for tasks such as file information retrieval, existence checks, and web crawling.

php Courses
php Courses
php Courses
How to Retrieve HTTP Response Headers in PHP Using get_headers()

In PHP development, obtaining the response headers of a web page or remote resource is often required. The get_headers() function provides a convenient way to fetch the headers of a target URL and returns them as an array.

Function Syntax

array get_headers(string $url, int $format = 0)
$url

is the target URL. $format is optional; when set to 0 (default) the function returns an associative array with both indexes and values, while 1 returns a simple indexed array.

Basic Usage Example

$url = "https://www.example.com";
$headers = get_headers($url);
// Print all response headers
print_r($headers);
// Print specific headers
echo $headers[0]; // First header (status line)
echo $headers[1]; // Second header (Date)

Typical output looks like:

Array (
    [0] => HTTP/1.1 200 OK
    [1] => Date: Thu, 19 Nov 2020 08:00:00 GMT
    [2] => Server: Apache/2.4.41
    [3] => Content-Type: text/html; charset=UTF-8
    [4] => Content-Length: 12345
    ...
)

Common Application Scenarios

Retrieve remote file information such as size and MIME type by examining the headers.

Check whether a remote file exists by inspecting the HTTP status code.

Use in web crawlers or network monitoring to decide further processing based on header data.

Note that get_headers() works only with the HTTP protocol; it cannot fetch headers for other protocols like FTP.

Conclusion

The get_headers() function is a practical tool for PHP developers, enabling easy access to HTTP response details such as status codes, dates, server information, and file metadata, thereby improving code usability and efficiency.

backendHTTPWeb developmentresponse headersget_headers
php Courses
Written by

php Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.