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 for retrieving and printing headers, and outlines common use cases such as file information, existence checks, and web crawling.
Overview: In PHP development, the get_headers() function conveniently obtains the response header information of a target URL and returns it as an array.
Function usage: get_headers() can retrieve the response headers of a specified URL and return them in array form. The basic syntax is:
array get_headers(string $url, int $format = 0)The $url parameter specifies the target URL. The optional $format parameter determines the format of the returned array: 0 (default) returns an associative array with indexes and values, while 1 returns an indexed array.
Code example:
$url = "https://www.example.com";
$headers = get_headers($url);
// Print all response header information
print_r($headers);
// Print specific header lines
echo $headers[0]; // First header line
echo $headers[1]; // Second header lineOutput example:
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
...
)Application scenarios for get_headers() include:
Obtaining remote file information such as size and MIME type.
Checking whether a remote file exists by examining HTTP status codes.
Web crawling and network monitoring, where header data helps decide further processing.
Note: get_headers() works only with the HTTP protocol and is not applicable to other protocols like FTP.
Summary: The get_headers() function is a practical PHP tool for retrieving various HTTP header details—including status codes, dates, server info, and file size—enhancing code usability and efficiency when used appropriately in backend development.
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.