【问题标题】:how to save user's profile pic in facebook using php如何使用 php 在 facebook 中保存用户的个人资料图片
【发布时间】:2011-03-25 08:10:02
【问题描述】:

您好,我正在尝试创建使用用户个人资料图片的应用程序。所以我编写了从 facebook 读取个人资料图片并将其保存在我的服务器上的代码。我使用以下代码

function GetImageFromUrl($link){
   $ch = curl_init();
curl_setopt($ch, CURLOPT_POST, 0);
curl_setopt($ch,CURLOPT_URL,$link);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result=curl_exec($ch);
curl_close($ch);
return $result;
}

$userpicpath = "http://graph.facebook.com/$uid/picture?type=normal";

$sourcecode = GetImageFromUrl($userpicpath);
$savefile = fopen("$uid-normal.jpg", "w"); //this is name of new file that i save
fwrite($savefile, $sourcecode);
fclose($savefile);

这里$uid是用户的id。

上面的代码不能正常工作。

但是当我在浏览器中复制 $userpicpath(即http://graph.facebook.com/$uid/picture?type=normal)并按回车键时,它将返回地址栏中图像的新路径并显示我想要的正确图像。如果我将地址栏中的这个新路径传递给我的函数,它会保存我想要的图像文件。

为什么会这样?我如何获得第二个图像路径并将其传递给程序中的函数。请帮帮我。

谢谢。

【问题讨论】:

    标签: php facebook


    【解决方案1】:

    Facebook 使用重定向来轻松嵌入网站。它通过发送 HTTP 302 重定向标头来完成此操作。由于我看到您使用的是 CURL,因此我根据我在网上找到的指南编写了我的示例。我还发布了如何通过 cURL 发送用户代理。这是我的 getFBResponse() 函数,可用于替换 $userpicpath 的分配。试试这个:$userpicpath = getFBRedirect();

    // Only calling the head
    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);
    
    // The response should be:
    /*
    HTTP/1.1 302 Found
    Location: http://www.iana.org/domains/example/
    */
    // So splitting on "Location: " should give an array of index 2, the URL you want being the second index (1)
    $theUrl = split($content, "Location: ");
    return $content[1];
    

    }

    【讨论】:

    • 感谢您的帮助。你的解决方案很有用。
    • 如果Location: 标头不是响应的最后一行(完全有可能),则此解决方案将非常脆弱。让 CURL 库正确解析标头要好得多,如下所述,它甚至可以为您跟踪重定向。
    【解决方案2】:

    尝试为您的请求设置 User-Agent 标头。 FB 和许多其他服务经常拒绝为未设置 User-Agent 的请求提供服务。

    编辑:可以这样做:

    curl_setopt($ch,CURLOPT_HTTPHEADER,array('User-Agent: AnythingYouLikeHere'));
    

    编辑 2: 关于重定向的部分也是如此。要让 cURL 自动处理重定向处理,您可以这样做:

    curl_setopt($ch,CURLOPT_FOLLOWLOCATION,true);
    

    【讨论】:

    • @user392406:已更新,请参见上面的示例。
    【解决方案3】:

    听起来像是重定向。那些PHP无法处理的,你需要找出图片的真实地址才能使用GetImageFromUrl

    【讨论】:

      【解决方案4】:

      您可以通过设置CURLOPT_FOLLOWLOCATION 选项告诉 CURL 遵循 Facebook 服务器返回的重定向;以下应该可以按需要工作:

      function GetImageFromUrl($link) {
          $ch = curl_init();
      
          curl_setopt($ch, CURLOPT_POST, 0);
          curl_setopt($ch, CURLOPT_URL, $link);
          curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
      
          # ADDED LINE:
          curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
      
          $result = curl_exec($ch);
          curl_close($ch);
      
          return $result;
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-06-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多