【问题标题】:file_get_contents is not able to read image from facebook image urlfile_get_contents 无法从 facebook 图片 url 读取图片
【发布时间】:2012-10-06 14:57:47
【问题描述】:

我有一个来自 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);

【问题讨论】:

  • 您的设置可能不允许 url_fopen。您可能需要改用 curl。
  • +1 ^ CURL 是一个更好的选择。
  • 我可以知道如何使用 curl 提取图像
  • 使用 curl 但没有得到任何响应
  • 这与 SSL 有关。改用 http:// 试试。或者在使用 CURL 时使用签名证书。

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


【解决方案1】:

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

<?php

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

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

【讨论】:

    【解决方案2】:

    您需要告诉 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;
    

    【讨论】:

      【解决方案3】:

      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);
      }
      

      【讨论】:

      • 可以放 header("User-Agent: My Image Downloader");并保持其他一切不变吗?
      • 不,这会将标头发送到请求 PHP 页面的浏览器。
      • 您也可以使用ini_set('user_agent', 'My Image Downloader'); 设置用户代理。
      • 啊,原来如此。我忘记了那个设置。
      猜你喜欢
      • 2012-01-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-04
      • 1970-01-01
      • 1970-01-01
      • 2021-01-24
      相关资源
      最近更新 更多