php Facebook API - 如何通过 Facebook API 获取 Facebook 用户的个人资料图片(无需用户“允许”应用程序)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2821061/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 07:46:14  来源:igfitidea点击:

Facebook API - How do I get a Facebook user's profile image through the Facebook API (without requiring the user to "Allow" the application)

phpfacebook

提问by John Himmelman

I'm working on a CMSthat fetches a user's profile image from their Facebook URL(that is, http://facebook.com/users_unique_url). How can I accomplish this? Is there a Faceboook API call that fetches a user's profile image URL without the user needing to Allowthe application?

我正在开发一个CMS,它从用户的 Facebook URL(即http://facebook.com/users_unique_url)中获取用户的个人资料图片。我怎样才能做到这一点?是否有一个 Faceboook API 调用可以在用户不需要允许应用程序的情况下获取用户的个人资料图片 URL ?

回答by Sarfraz

Simply fetch the data through this URL:

只需通过此URL获取数据:

http://graph.facebook.com/userid_here/picture

http://graph.facebook.com/userid_here/picture

Replace userid_herewith id of the user you want to get the photo of. You can also use HTTPS as well.

替换userid_here为您想要获取照片的用户的 ID。您也可以使用 HTTPS。

You can use the PHP's file_get_contentsfunction to read that URL and process the retrieved data.

您可以使用 PHP 的file_get_contents函数来读取该 URL 并处理检索到的数据。

Resource:

资源:

http://developers.facebook.com/docs/api

http://developers.facebook.com/docs/api

Note:In php.ini, you need to make sure that the OpenSSLextension is enabled to use thefile_get_contentsfunction of PHP to read that URL.

注意:在 中php.ini,您需要确保已启用OpenSSL扩展才能使用file_get_contentsPHP的功能读取该 URL。

回答by neiker

To show:

显示:

50x50 pixels

50x50 像素

<img src="//graph.facebook.com/{{fid}}/picture">

200 pixels width

200 像素宽

<img src="//graph.facebook.com/{{fid}}/picture?type=large">

To save (using PHP)

保存(使用 PHP)

NOTE: Don't use this. See @Foreever's comment below.

注意:不要使用这个。请参阅下面的@Foreever 评论。

$img = file_get_contents('https://graph.facebook.com/'.$fid.'/picture?type=large');
$file = dirname(__file__).'/avatar/'.$fid.'.jpg';
file_put_contents($file, $img);

Where $fid is your user id on Facebook.

$fid 是您在 Facebook 上的用户 ID。

NOTE: In case of images marked as "18+" you will need a valid access_token from a 18+ user:

注意:如果图像标记为“18+”,您将需要来自 18+ 用户的有效 access_token:

<img src="//graph.facebook.com/{{fid}}/picture?access_token={{access_token}}">

UPDATE 2015:

2015 年更新:

Graph API v2.0 can't be queried using usernames, you shoulduse userIdalways.

Graph API v2.0 不能使用用户名查询,您应该userId始终使用。

回答by Gunnar Karlsson

UPDATE:

更新

Starting end August 2012, the API has been updated to allow you to retrieve user's profile pictures in varying sizes. Add the optional width and height fields as URL parameters:

从 2012 年 8 月开始,API 已更新,允许您检索不同大小的用户个人资料图片。添加可选的宽度和高度字段作为 URL 参数:

https://graph.facebook.com/USER_ID/picture?width=WIDTH&height=HEIGHT

where WIDTHand HEIGHTare your requested dimension values.

哪里WIDTHHEIGHT是您请求的维度值。

This will return a profile picture with a minimum size of WIDTHx HEIGHTwhile trying to preserve the aspect ratio. For example,

这将返回最小尺寸为WIDTHx的个人资料图片,HEIGHT同时尝试保留纵横比。例如,

https://graph.facebook.com/redbull/picture?width=140&height=110

returns

返回

    {
      "data": {
        "url": "https://fbcdn-profile-a.akamaihd.net/hprofile-ak-ash4/c0.19.180.142/s148x148/2624_134501175351_4831452_a.jpg",
        "width": 148,
        "height": 117,
        "is_silhouette": false
      }
   }

END UPDATE

结束更新

To get a user's profile picture, call

要获取用户的个人资料图片,请致电

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

where USER_IDcan be the user id number or the user name.

其中USER_ID可以是用户 ID 号或用户名。

To get a user profile picture of a specific size, call

要获取特定大小的用户个人资料图片,请致电

https://graph.facebook.com/USER_ID/picture?type=SIZE

where SIZEshould be replaced with one of the words

whereSIZE应该替换为其中一个词

square
small
normal
large

depending on the size you want.

取决于你想要的尺寸。

This call will return a URLto a single image with its size based on your chosen type parameter.

此调用将返回单个图像的URL,其大小基于您选择的类型参数。

For example:

例如:

https://graph.facebook.com/USER_ID/picture?type=small

returns a URL to a small version of the image.

返回图像的小版本的 URL。

The API only specifies the maximum size for profile images, not the actual size.

API 只指定了个人资料图片的最大尺寸,而不是实际尺寸。

Square:

正方形:

maximum width and height of 50 pixels.

最大宽度和高度为 50 像素。

Small

小的

maximum width of 50 pixels and a maximum height of 150 pixels.

最大宽度为 50 像素,最大高度为 150 像素。

Normal

普通的

maximum width of 100 pixels and a maximum height of 300 pixels.

最大宽度为 100 像素,最大高度为 300 像素。

Large

大的

maximum width of 200 pixels and a maximum height of 600 pixels.

最大宽度为 200 像素,最大高度为 600 像素。

If you call the default USER_ID/picture you get the square type.

如果您调用默认的 USER_ID/picture,您将获得方形类型。

CLARIFICATION

澄清

If you call (as per above example)

如果你打电话(按照上面的例子)

https://graph.facebook.com/redbull/picture?width=140&height=110

it will return a JSONresponse if you're using one of the Facebook SDKs request methods. Otherwise it will return the image itself. To always retrieve the JSON, add:

如果您使用 Facebook SDK 请求方法之一,它将返回JSON响应。否则它将返回图像本身。要始终检索 JSON,请添加:

&redirect=false

like so:

像这样:

https://graph.facebook.com/redbull/picture?width=140&height=110&redirect=false

回答by NaturalBornCamper

To get the image URL, NOT binary content:

要获取图像 URL,而不是二进制内容:

$url = "http://graph.facebook.com/$fbId/picture?type=$size";

$headers = get_headers($url, 1);

if( isset($headers['Location']) )
    echo $headers['Location']; // string
else
    echo "ERROR";

You must use your FACEBOOK ID, NOT USERNAME. You can get your facebook id there:

您必须使用您的 FACEBOOK ID,而不是用户名。您可以在那里获取您的 facebook id:

http://findmyfbid.com/

http://findmyfbid.com/

回答by Armand

Simple one-line code to save FULL size profile image on your server.

简单的一行代码,可在您的服务器上保存完整尺寸的个人资料图像。

<?php

copy("https://graph.facebook.com/FACEBOOKID/picture?width=9999&height=9999", "picture.jpg");

?>

This will only work if openssl is enabled in php.ini.

这仅在 php.ini 中启用 openssl 时才有效。

回答by sckd

Added this as a comment to accepted answer, but felt it deserved a longer explanation. Starting around April 2015 this will probably be raised a few times.

将此添加为对已接受答案的评论,但认为它值得更长的解释。从 2015 年 4 月左右开始,这可能会提高几次。

As of V2 of the graph api the accepted answer no longer works using a username. So now you need the userid first, and you can no longer use a username to get this. To further complicate matters, for privacy reasons, Facebook is now changing userid's per app (see https://developers.facebook.com/docs/graph-api/reference/v2.2/user/and https://developers.facebook.com/docs/apps/upgrading/#upgrading_v2_0_user_ids), so you will have to have some kind of proper authentication to retrieve a userid you can use. Technically the profile pic is still public and available at /userid/picture (see docs at https://developers.facebook.com/docs/graph-api/reference/v2.0/user/pictureand this example user: http://graph.facebook.com/v2.2/4/picture?redirect=0) however figuring out a user's standard userid seems impossible based just on their profile - your app would need to get them to approve interaction with the app which for my use case (just showing a profile pic next to their FB profile link) is overkill.

从图形 api 的 V2 开始,接受的答案不再使用用户名有效。所以现在你首先需要用户名,你不能再使用用户名来获得它。更复杂的是,出于隐私原因,Facebook 现在正在更改每个应用程序的用户 ID(请参阅https://developers.facebook.com/docs/graph-api/reference/v2.2/user/https://developers.facebook .com/docs/apps/upgrading/#upgrading_v2_0_user_ids),因此您必须进行某种适当的身份验证才能检索可以使用的用户 ID。从技术上讲,个人资料图片仍然是公开的,可在 /userid/picture 处获得(请参阅https://developers.facebook.com/docs/graph-api/reference/v2.0/user/picture 上的文档和此示例用户:http: //graph.facebook.com/v2.2/4/picture?redirect=0) 然而,仅仅根据他们的个人资料找出用户的标准用户 ID 似乎是不可能的 - 您的应用程序需要让他们批准与应用程序的交互,这对于我的用例(仅在他们的 FB 个人资料链接旁边显示个人资料图片)是矫枉过正的。

If someone has figured out a way to get the profile pic based on username, or alternatively, how to get a userid (even an alternating one) to use to retrieve a profile pic, please share! In the meantime, the old graph url still works until April 2015.

如果有人想出了一种根据用户名获取个人资料图片的方法,或者如何获取用户 ID(甚至是交替的)以用于检索个人资料图片,请分享!与此同时,旧的图表网址在 2015 年 4 月之前仍然有效。

回答by benjaminlotan

One way is to use the code Gamlet postedin his answer:

一种方法是使用Gamlet在他的回答中发布的代码:

  • Save it as curl.php

  • Then in your file:

    require 'curl.php';
    
    $photo="https://graph.facebook.com/me/picture?access_token=" . $session['access_token'];
    $sample = new sfFacebookPhoto;
    $thephotoURL = $sample->getRealUrl($photo);
    echo $thephotoURL;
    
  • 将其另存为 curl.php

  • 然后在您的文件中:

    require 'curl.php';
    
    $photo="https://graph.facebook.com/me/picture?access_token=" . $session['access_token'];
    $sample = new sfFacebookPhoto;
    $thephotoURL = $sample->getRealUrl($photo);
    echo $thephotoURL;
    

I thought I would post this, because it took me a bit of time to figure out the particulars... Even though profile pictures are public, you still need to have an access token in there to get it when you curlit.

我想我会发布这个,因为我花了一些时间来弄清楚细节......即使个人资料图片是公开的,你仍然需要在那里有一个访问令牌才能在你卷曲它时获得它。

回答by Hamlet

There is way to do that ;)

有办法做到这一点;)

Thanks to "http://it.toolbox.com/wiki/index.php/Use_curl_from_PHP_-_processing_response_headers":

感谢“ http://it.toolbox.com/wiki/index.php/Use_curl_from_PHP_-_processing_response_headers”:

<?php

    /**
     * Facebook user photo downloader
     */

    class sfFacebookPhoto {

        private $useragent = 'Loximi sfFacebookPhoto PHP5 (cURL)';
        private $curl = null;
        private $response_meta_info = array();
        private $header = array(
                "Accept-Encoding: gzip,deflate",
                "Accept-Charset: utf-8;q=0.7,*;q=0.7",
                "Connection: close"
            );

        public function __construct() {
            $this->curl = curl_init();
            register_shutdown_function(array($this, 'shutdown'));
        }

        /**
         * Get the real URL for the picture to use after
         */
        public function getRealUrl($photoLink) {
            curl_setopt($this->curl, CURLOPT_HTTPHEADER, $this->header);
            curl_setopt($this->curl, CURLOPT_RETURNTRANSFER, false);
            curl_setopt($this->curl, CURLOPT_HEADER, false);
            curl_setopt($this->curl, CURLOPT_USERAGENT, $this->useragent);
            curl_setopt($this->curl, CURLOPT_CONNECTTIMEOUT, 10);
            curl_setopt($this->curl, CURLOPT_TIMEOUT, 15);
            curl_setopt($this->curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
            curl_setopt($this->curl, CURLOPT_URL, $photoLink);

            //This assumes your code is into a class method, and
            //uses $this->readHeader as the callback function.
            curl_setopt($this->curl, CURLOPT_HEADERFUNCTION, array(&$this, 'readHeader'));
            $response = curl_exec($this->curl);
            if (!curl_errno($this->curl)) {
                $info = curl_getinfo($this->curl);
                var_dump($info);
                if ($info["http_code"] == 302) {
                    $headers = $this->getHeaders();
                    if (isset($headers['fileUrl'])) {
                        return $headers['fileUrl'];
                    }
                }
            }
            return false;
        }


        /**
         * Download Facebook user photo
         *
         */
        public function download($fileName) {
            curl_setopt($this->curl, CURLOPT_HTTPHEADER, $this->header);
            curl_setopt($this->curl, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($this->curl, CURLOPT_HEADER, false);
            curl_setopt($this->curl, CURLOPT_USERAGENT, $this->useragent);
            curl_setopt($this->curl, CURLOPT_CONNECTTIMEOUT, 10);
            curl_setopt($this->curl, CURLOPT_TIMEOUT, 15);
            curl_setopt($this->curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
            curl_setopt($this->curl, CURLOPT_URL, $fileName);
            $response = curl_exec($this->curl);
            $return = false;
            if (!curl_errno($this->curl)) {
                $parts = explode('.', $fileName);
                $ext = array_pop($parts);
                $return = sfConfig::get('sf_upload_dir') . '/tmp/' . uniqid('fbphoto') . '.' . $ext;
                file_put_contents($return, $response);
            }
            return $return;
        }

        /**
         * cURL callback function for reading and processing headers.
         * Override this for your needs.
         *
         * @param object $ch
         * @param string $header
         * @return integer
         */
        private function readHeader($ch, $header) {

            //Extracting example data: filename from header field Content-Disposition
            $filename = $this->extractCustomHeader('Location: ', '\n', $header);
            if ($filename) {
                $this->response_meta_info['fileUrl'] = trim($filename);
            }
            return strlen($header);
        }

        private function extractCustomHeader($start, $end, $header) {
            $pattern = '/'. $start .'(.*?)'. $end .'/';
            if (preg_match($pattern, $header, $result)) {
                return $result[1];
            }
            else {
                return false;
            }
        }

        public function getHeaders() {
            return $this->response_meta_info;
        }

        /**
         * Cleanup resources
         */
        public function shutdown() {
            if($this->curl) {
                curl_close($this->curl);
            }
        }
    }

回答by Xawier

Working PHP (HTTP GET) solution from April 2015 (without PHP 5 SDK):

2015 年 4 月的 PHP (HTTP GET) 解决方案(没有 PHP 5 SDK):

function get_facebook_user_avatar($fbId){
        $json = file_get_contents('https://graph.facebook.com/v2.5/'.$fbId.'/picture?type=large&redirect=false');
        $picture = json_decode($json, true);
        return $picture['data']['url'];
}

You can change 'type' in parametr:

您可以在参数中更改“类型”:

Square:

正方形:

maximum width and height of 50 pixels.

最大宽度和高度为 50 像素。

Small

小的

maximum width of 50 pixels and a maximum height of 150 pixels.

最大宽度为 50 像素,最大高度为 150 像素。

Normal

普通的

maximum width of 100 pixels and a maximum height of 300 pixels.

最大宽度为 100 像素,最大高度为 300 像素。

Large

大的

maximum width of 200 pixels and a maximum height of 600 pixels.

最大宽度为 200 像素,最大高度为 600 像素。

回答by Erroid

I was thinking - maybe IDwill be a useful tool. Every time a user creates a new account it should get a higher ID. I googled and found that there is a method to estimate the account creation date by ID and Massoud Seifi from metadatascience.com gathered some good data about it.

我在想 - 也许ID会是一个有用的工具。每次用户创建一个新帐户时,它都应该获得一个更高的 ID。我用谷歌搜索,发现有一种方法可以通过 ID 估计帐户创建日期,而来自 metadatascience.com 的 Massoud Seifi 收集了一些关于它的好数据。

Enter image description here

在此处输入图片说明

Read this article:

阅读这篇文章:

http://metadatascience.com/2013/03/11/inferring-facebook-account-creation-date-from-facebook-user-id/

http://metadatascience.com/2013/03/11/inferring-facebook-account-creation-date-from-facebook-user-id/

And here are some IDs to download:

这里有一些 ID 可供下载:

http://metadatascience.com/2013/03/14/lookup-table-for-inferring-facebook-account-creation-date-from-facebook-user-id/

http://metadatascience.com/2013/03/14/lookup-table-for-inferring-facebook-account-creation-date-from-facebook-user-id/