php

PHP获取远程图片头部信息的几种方法

dafenqi
2023-12-30 / 0 评论 / 11 阅读 / 正在检测是否收录...

PHP获取远程图片头部信息的几种方法

PHP是一门流行的Web编程语言,用于开发动态网站和Web应用程序。在Web开发中,经常需要获取远程图片的header头部信息。本文将介绍几种PHP获取远程图片header头部的方法以及相应的示例。

方法一:使用get_headers函数

get_headers函数可以获取指定URL的响应头信息,其中包含了图片的header头部信息。步骤如下:

$url = "https://www.example.com/image.jpg";
$headers = get_headers($url, 1);
print_r($headers);

输出结果:

Array
(
    [0] => HTTP/1.1 200 OK
    [1] => Date: Mon, 18 Oct 2021 10:56:37 GMT
    [2] => Server: Apache
    [3] => Last-Modified: Thu, 10 Oct 2019 12:10:00 GMT
    [4] => ETag: "3840-59587a4f2bea7"
    [5] => Accept-Ranges: bytes
    [6] => Content-Length: 14336
    [7] => Cache-Control: max-age=604800
    [8] => Expires: Mon, 25 Oct 2021 10:56:37 GMT
    [9] => Content-Type: image/jpeg
)

方法二:使用curl函数

curl函数是一种强大的PHP库,用于从Web服务器上获取数据,包括图片的header头部信息。步骤如下:

$url = "https://www.example.com/image.jpg";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$headers = curl_exec($ch);
curl_close($ch);
print_r($headers);

示例输出结果:

HTTP/1.1 200 OK
Date: Mon, 18 Oct 2021 11:03:18 GMT
Server: Apache
Last-Modified: Thu, 10 Oct 2019 12:10:00 GMT
ETag: "3840-59587a4f2bea7"
Accept-Ranges: bytes
Content-Length: 14336
Cache-Control: max-age=604800
Expires: Mon, 25 Oct 2021 11:03:18 GMT
Content-Type: image/jpeg

方法三:使用apache_request_headers函数

apache_request_headers函数可以获取当前请求的header头部信息,包括图片的header头部信息。步骤如下:

$url = "https://www.example.com/image.jpg";
$context = stream_context_create(array('http' => array('method' => 'HEAD')));
$file_headers = get_headers($url, 1, $context);
$headers = array();
foreach ($file_headers as $key => $val) {
    if (strpos($key, 'HTTP') === 0) {
        $headers['Status'] = $val;
    } else {
        $headers[$key] = $val;
    }
}
print_r($headers);

示例输出结果:

Array
(
    [Status] => HTTP/1.1 200 OK
    [Date] => Mon, 18 Oct 2021 11:07:17 GMT
    [Server] => Apache
    [Last-Modified] => Thu, 10 Oct 2019 12:10:00 GMT
    [ETag] => "3840-59587a4f2bea7"
    [Accept-Ranges] => bytes
    [Content-Length] => 14336
    [Cache-Control] => max-age=604800
    [Expires] => Mon, 25 Oct 2021 11:07:17 GMT
    [Content-Type] => image/jpeg
)

总结

本文介绍了几种PHP获取远程图片header头部的方法以及相应的示例。使用这些方法,我们可以快速方便地获取远程图片的header头部信息,从而为Web开发和数据分析提供帮助。

0

Deprecated: strtolower(): Passing null to parameter #1 ($string) of type string is deprecated in /www/wwwroot/testblog.58heshihu.com/var/Widget/Archive.php on line 1032

评论 (0)

取消