簡體   English   中英

從 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 就會自動跟隨該重定向並為您獲取真實圖像。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM