获取Facebook真实资料图片网址

时间:2010-08-20 22:08:10

标签: php image api facebook url

根据Facebook图形API,我们可以使用此示例请求用户个人资料图片:

https://graph.facebook.com/1489686594/picture

我们不需要任何令牌,因为它是公共信息。

但上一个链接的真实图片网址为:http://profile.ak.fbcdn.net/hprofile-ak-snc4/hs356.snc4/41721_1489686594_527_q.jpg

如果您在浏览器上输入第一个链接,它会将您重定向到第二个链接。

有没有办法通过知道第一个链接来获取PHP的完整URL(第二个链接)?

我有一个函数可以从URL获取图像以将其存储在数据库中,但只有在获取完整图像URL时才能正常工作。

由于

5 个答案:

答案 0 :(得分:20)

kire是对的,但对于您的用例更好的解决方案如下:

    // get the headers from the source without downloading anything
    // there will be a location header wich redirects to the actual url
    // you may want to put some error handling here in case the connection cant be established etc...
    // the second parameter gives us an assoziative array and not jut a sequential list so we can right away extract the location header
    $headers = get_headers('https://graph.facebook.com/1489686594/picture',1);
    // just a precaution, check whether the header isset...
    if(isset($headers['Location'])) {
        $url = $headers['Location']; // string
    } else {
        $url = false; // nothing there? .. weird, but okay!
    }
    // $url contains now the url of the profile picture, but be careful it might very well be only temporary! there's a reason why facebok does it this way ;)
    // the code is untested!

答案 1 :(得分:7)

您可以使用FQL获取它:

select pic_square from user where uid=1489686594

返回:

[
  {
    "pic_square": "http://profile.ak.fbcdn.net/hprofile-ak-snc4/hs356.snc4/41721_1489686594_527_q.jpg"
  }
]

此外,您可以通过网址改善您的功能。如果您使用curl,则可以自动关注重定向标题。

答案 2 :(得分:2)

请注意,The Surrican的答案(以及可能的其他人)可以大大增加您的脚本的响应时间(在我的服务器上大约+ 500ms)。这是因为服务器向facebook发出请求(因为get_headers())并且执行时间(排除计算)从此延伸:

  • 浏览器 - >服务器
  • 服务器 - >浏览器

到此:

  • 浏览器 - >服务器
  • 服务器 - > facebook(要求:get_headers)
  • facebook - >服务器(响应:get_headers)
  • 服务器 - >浏览器

这增加了上述500毫秒的延迟。您可能应该考虑在服务器上缓存真实网址或通过JavaScript加载个人资料图片。至少看一下你之前和之后的回复时间;)

答案 3 :(得分:2)

@The Surrican,
好的代码!这是一个干净的代码函数,用于这样的过程!

function get_raw_facebook_avatar_url($uid)
{
    $array = get_headers('https://graph.facebook.com/'.$uid.'/picture?type=large', 1);
    return (isset($array['Location']) ? $array['Location'] : FALSE);
}

这将返回RAW facebook头像图片网址。随便用它随意做任何事情!

答案 4 :(得分:0)

您还可以在网址末尾添加?redirect=false,然后直接解析JSON响应。

在您的示例中:https://graph.facebook.com/1489686594/picture?redirect=false

此处提供更多信息https://developers.facebook.com/docs/graph-api/reference/user/picture/