Using PHP get_headers() to Retrieve HTTP Response Headers
This article explains how to use PHP's get_headers() function to fetch HTTP response headers from a URL, describes its syntax and parameters, provides code examples, shows typical output, and discusses common use cases such as file information retrieval, existence checks, and web crawling.
In PHP development, obtaining the response headers of a web page or remote resource is often required. The built‑in get_headers() function makes this easy by returning the headers of a target URL as an array.
The basic syntax of the function is:
array get_headers(string $url, int $format = 0)The $url parameter specifies the target URL. The optional $format parameter controls the return format: 0 (default) returns an associative array with index and value, while 1 returns a simple indexed array.
Example usage:
$url = "https://www.example.com";
$headers = get_headers($url);
// Print all response headers
print_r($headers);
// Print specific headers
echo $headers[0]; // first header
echo $headers[1]; // second headerTypical output of the above code 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 for get_headers() include:
Retrieving remote file information such as size and MIME type.
Checking whether a remote file exists by examining the HTTP status code.
Supporting web crawlers and network monitoring tools by pre‑checking response headers before further processing.
Note that get_headers() works only with the HTTP protocol and cannot be used for other protocols like FTP.
Summary
The get_headers() function is a practical PHP utility for obtaining HTTP response header information, enabling developers to access status codes, dates, server details, file sizes, and more, thereby improving code usability and efficiency in real‑world projects.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.