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.

php Courses
php Courses
php Courses
Master PHP’s get_headers(): Retrieve HTTP Headers with Code Examples

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)
$url

is 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 header

Sample 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.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

HTTPWeb DevelopmentPHPHeadersget_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.