Master PHP’s get_headers(): Retrieve HTTP Headers with Code Examples
Learn how to use PHP’s get_headers() function to fetch HTTP response headers, understand its parameters and formats, see practical code snippets, and explore common scenarios such as checking remote files, obtaining file metadata, and building web crawlers.
In PHP development we often need to obtain the response headers of a web page or remote resource. The PHP function get_headers() conveniently retrieves the target URL’s response headers and returns them as an array.
The get_headers() function can fetch the specified URL’s response headers and return them in array form. Its basic syntax is:
array get_headers(string $url, int $format = 0) $urlis the target URL. $format is optional; when set to 0 (default) it returns an associative array with indexes and values, and when set to 1 it returns an indexed array.
Example code:
$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 headerSample output:
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 Use Cases
Obtain remote file information such as size and MIME type by reading response headers.
Check whether a remote file exists by examining the HTTP status code.
Use in crawlers and network monitoring to decide further processing based on header data.
Note that get_headers() works only with HTTP protocol responses and is not applicable to other protocols like FTP.
Conclusion
The get_headers() function is a practical PHP tool for retrieving various HTTP header information, such as status codes, dates, server details, and file sizes, which can improve code usability and efficiency when applied appropriately.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
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.
