file_get_contents无法从facebook图片网址中读取图片

时间:2012-10-16 13:34:28

标签: php facebook facebook-graph-api curl file-get-contents

我有来自facebook的图片网址:

https://fbcdn-sphotos-e-a.akamaihd.net/hphotos-ak-prn1/s720x720/156510_443901075651849_1975839315_n.jpg

我需要在当地保存这个。当我使用file_get_contents时,它会给出错误failed to open stream。当我在浏览器中打开图像时显示正常。我只是明白该怎么做。

因为我以下列方式使用curl并且根本没有得到任何响应

$ url = https://fbcdn-sphotos-e-a.akamaihd.net/hphotos-ak-prn1/s720x720/156510_443901085651849_1975839315_n.jpg;

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, 0);
$response = curl_exec($ch);
curl_close($ch);
$filename = 'ex'.$src['photo_id'].'.jpg';
$imgRes = imagecreatefromstring($response);
imagejpeg($imgRes, $filename, 70);

header("Content-Type: image/jpg");
imagejpeg($imgRes, NULL, 70);

3 个答案:

答案 0 :(得分:3)

这是因为您正在请求一个安全的URL,而您的服务器可能在没有配置的情况下不支持它。您可以使用CURL来请求具有有效证书的URL,也可以尝试在没有SSL的情况下请求它:

<?php

$file = 'http://url/to_image.jpg';
$data = file_get_contents($file);

header('Content-type: image/jpg');
echo $data;

答案 1 :(得分:1)

您需要告诉cURL您不要验证SSL连接。

以下内容经过测试并有效。

$url = "https://******";


$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // ignore SSL verifying
curl_setopt($ch, CURLOPT_HEADER, 0);
$response = curl_exec($ch);
curl_close($ch);

header("Content-Type: image/jpg");
echo $response;

答案 2 :(得分:0)

Facebook最有可能需要有效的用户代理字符串并拒绝您的请求,因为file_get_contents在访问远程文件时不会发送请求。

你可以用这个:

if( $f = fsockopen($host="fbcdn-sphotos-e-a-.akamaihd.net",80)) {
    fputs($f,"GET /hphotos-ak-prn1/........ HTTP/1.0\r\n"
            ."Host: ".$host."\r\n"
            ."User-Agent: My Image Downloader\r\n\r\n");
    $ret = "";
    $headers = true;
    while(!feof($f)) {
        $line = fgets($f);
        if( $headers) {
            if( trim($line) == "") $headers = false;
        }
        else $ret .= $line;
    }
    fclose($f);
    file_put_contents("mylocalfile.png",$ret);
}