Using PHP get_headers() to Retrieve HTTP Response Headers
This article explains the PHP get_headers() function, its syntax, parameters, and usage examples, demonstrates how to retrieve and display HTTP response headers from a URL, and discusses common application scenarios such as checking remote file existence, obtaining file metadata, and supporting web crawling or monitoring.
The get_headers() function in PHP provides a convenient way to fetch the response headers of a remote URL and returns them as an array.
Its basic syntax 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 indexes and values, 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 (status line)
echo $headers[1]; // Second headerTypical 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 include:
Obtaining remote file information such as size and MIME type by inspecting the headers.
Checking whether a remote file exists or is reachable by examining the HTTP status code.
Supporting web crawlers and network monitoring tools that need to verify a URL’s status before further processing.
Note that get_headers() works only with the HTTP protocol and cannot be used for other protocols like FTP.
In summary, get_headers() is a practical PHP function that simplifies the retrieval of HTTP response header data, helping developers to access status codes, dates, server details, file sizes, and other metadata, thereby improving code usability and efficiency.
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.