仅从cURL请求的标头中获取位置


Getting just the Location from Header of cURL Request

我试图在重定向后检索图像的位置URL,但似乎无法使其工作。我以前从未使用过cURL,但从我所做的研究来看,我需要它才能从Facebook上获得图像。到目前为止,这是我的代码:

function getImage($url) {
$ch = curl_init();
// Only calling the head
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, true); // header will be at output
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'HEAD'); // HTTP request is 'HEAD'
$content = curl_exec($ch);
curl_close($ch);
return $content;
}
$image = explode("Location: ", getImage("http://graph.facebook.com/553451657/picture?type=large"));
print_r($image);

但我的回答是:

HTTP/1.1 302 Found Access-Control-Allow-Origin: * Cache-Control: private, no-cache, no-store, must-revalidate Content-Type: image/jpeg Expires: Sat, 01 Jan 2000 00:00:00 GMT Location: http://profile.ak.fbcdn.net/hprofile-ak-snc4/161877_553451657_798840908_n.jpg Pragma: no-cache X-FB-Rev: 590433 X-FB-Debug: WH1uJvIjUqiLT8ezVPdude8VKYnXjAHRlFaP8gqF9fI= Date: Fri, 13 Jul 2012 17:56:09 GMT Connection: keep-alive Content-Length: 0 Array ( [0] => 1 ) 

如何获取位置部分("http://profile.ak.fbcdn.net/hprofile-ak-snc4/161877_553451657_798840908_n.jpg")?

您可以在标头上执行一个函数:

            $headers = [];
            curl_setopt($curl, CURLOPT_HEADERFUNCTION, function ($ch, $header) use (&$headers) {
                $matches = array();
                if ( preg_match('/^([^:]+)'s*:'s*([^'x0D'x0A]*)'x0D?'x0A?$/', $header, $matches) )
                {
                    $headers[$matches[1]][] = $matches[2];
                }
                return strlen($header);
            });

(此处可见)

然后将其存储在$headers["Location"][0]中。

我也和你一样,试图以这种方式获取fb页面图像,这似乎不需要PHP SDK、应用程序权限或access_token,但可能有一些限制(有人知道吗?)

如何获取定位部分

获得Location标头不是您的主要目标,对吧?您想从重定向到的地址获取图像,对吗?

因此,只需设置选项CURLOPT_FOLLOWLOCATION,cURL将自动跟随重定向并为您获取真实图像。