这是使用带有 CURLOPT_WRITEFUNCTION 回调函数的 cURL 的解决方案。在其中,我检查传入的标头以查找内容类型。如果这不是我们想要的,它会告诉 cURL 中止,这样您就不会浪费时间获取请求的正文。
$ch = curl_init('http://stackoverflow.com/');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, true);
$data = '';
$haveHeader = false;
curl_setopt($ch, CURLOPT_WRITEFUNCTION, function($ch, $chunk) use (&$haveHeader, &$data) {
if (!$haveHeader && ($chunk == "\n" || $chunk == "\r\n")) {
// detected end of header
$haveHeader = true;
} else if (!$haveHeader) {
// detected content type
if (preg_match('/content-type:\s*([^;]+)/i', $chunk, $matches)) {
$contentType = strtolower($matches[1]);
// check if content type is what we want
if ($contentType != 'text/html' && strpos($contentType, 'image/') === false) {
// tell curl to abort
return false;
}
}
} else {
// append to data (body/content)
$data .= $chunk;
}
return strlen($chunk);
});
if (curl_exec($ch)) {
// use $data here
echo strlen($data);
}