PHP CURL 获取响应头与内容

PHP的CURL默认是只会返回请求的响应体,当我们需要响应头的时候,需要在请求的时候设置相应的参数,参考代码:

$url = 'https://img.games.com/logo/participant/550';

function http_get_data($url)
{
echo "CURL 请求时间结束 " . time() . PHP_EOL;
$headers = [
"Authorization: Bearer eyJhbGciOiJIUz"
];

$ch = curl_init();
# 设置请求方式
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
# HTTPS 验证
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
# 请求URL
curl_setopt($ch, CURLOPT_URL, $url);
# 请求头设置
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
# 是否输出响应头
curl_setopt($ch, CURLOPT_HEADER, true);
ob_start();
curl_exec($ch);
$return_content = ob_get_contents();
ob_end_clean();
// $return_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
# 获取请求头的大小
$headerSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
# 根据请求头的大小,截取到头信息与内容信息
$header = substr($return_content, 0, $headerSize);
echo $header;
# 从头信息大小的位置开始到结尾为响应内容
return substr($return_content, $headerSize);
}
$return_content = http_get_data($url);

Tips: 在设置好输出响应头时,将返回类似以下内容

 HTTP/1.1 200 OK
Content-Type: image/svg+xml
Content-Length: 3436
Connection: keep-alive
x-amz-id-2: UO/YvMxKVUY7Myd
x-amz-request-id: 0F51AFAEC262EF43
Date: Wed, 04 Mar 2020 02:43:32 GMT
Last-Modified: Tue, 17 Dec 2019 16:43:46 GMT
ETag: "f49194651b539640ffc2123c0522b0b5"
x-amz-meta-etag: "5b7c1aa7-d6c"
x-amz-meta-lastchecked: 1576601025259
x-amz-version-id: 6AQLQdEYhw6e7n
Accept-Ranges: bytes
Server: AmazonS3
Vary: Accept-Encoding
X-Cache: Hit from cloudfront
Via: 1.1 340d837dff.cloudfront.net (CloudFront)
X-Amz-Cf-Pop: NRT20-C2
X-Amz-Cf-Id: gdHGDD0gasKv8Gb5jQ==
Age: 3831

从这行开始,之前都是响应头,下面就是响应内容

所以需要根据响应的头大小,做字符串的截取

Tips:如果只需要响应头,不要响应内容,则可以添加如下设置

curl_setopt($ch, CURLOPT_NOBODY, true)

Tips:如果需要返回请求头,则添加如下设置

curl_setopt($ch, CURLINFO_HEADER_OUT, true);

分类: