简体   繁体   English

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

[英]Facebook API - How do I get a Facebook user's profile image through the Facebook API (without requiring the user to “Allow” the application)

I'm working on a CMS that fetches a user's profile image from their Facebook URL (that is, http://facebook.com/users_unique_url ). 我正在使用一个CMS ,该CMS可从其Facebook URL (即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 Allow the application? 是否有一个Faceboook API调用可以获取用户的个人资料图像URL,而无需用户允许该应用程序?

Simply fetch the data through this URL : 只需通过以下URL获取数据:

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

Replace userid_here with id of the user you want to get the photo of. userid_here替换为您要获取照片的用户的ID。 You can also use HTTPS as well. 您也可以使用HTTPS。

You can use the PHP's file_get_contents function 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 OpenSSL extension is enabled to use the file_get_contents function of PHP to read that URL. 注意:php.ini ,您需要确保已启用OpenSSL扩展以使用PHP的file_get_contents函数来读取该URL。

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 . 注意: 请勿使用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 should use userId always. 不能使用用户名查询Graph API v2.0,您应该始终使用userId

UPDATE : 更新

Starting end August 2012, the API has been updated to allow you to retrieve user's profile pictures in varying sizes. 从2012年8月底开始,API已更新,可以检索大小不同的用户个人资料图片。 Add the optional width and height fields as URL parameters: 添加可选的width和height字段作为URL参数:

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

where WIDTH and HEIGHT are your requested dimension values. 其中WIDTHHEIGHT是您要求的尺寸值。

This will return a profile picture with a minimum size of WIDTH x HEIGHT while trying to preserve the aspect ratio. 尝试保留宽高比时,这将返回最小尺寸为WIDTH x HEIGHT的个人资料图片。 For example, 例如,

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_ID can 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 SIZE should be replaced with one of the words 其中“ SIZE应替换为以下单词之一

square
small
normal
large

depending on the size you want. 取决于您想要的大小。

This call will return a URL to a single image with its size based on your chosen type parameter. 该调用将根据您选择的type参数返回一个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 /图片,则会得到正方形。

CLARIFICATION 澄清说明

If you call (as per above example) 如果您致电(按照上述示例)

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

it will return a JSON response if you're using one of the Facebook SDKs request methods . 如果您使用Facebook SDK的请求方法之一,它将返回JSON响应。 Otherwise it will return the image itself. 否则它将返回图像本身。 To always retrieve the JSON, add: 要始终检索JSON,请添加:

&redirect=false

like so: 像这样:

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

To get the image URL, NOT binary content: 要获取图片网址,而不是二进制内容:

$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. 您必须使用FACEBOOK ID,而不是USERNAME。 You can get your facebook id there: 您可以在那里找到您的facebook ID:

http://findmyfbid.com/ http://findmyfbid.com/

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时,此方法才有效。

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. 从图api的V2版本开始,接受的答案不再使用用户名起作用。 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. 出于隐私原因,使事情更加复杂的是,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。 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/picture and 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. 从技术上讲,个人资料图片仍然是公开的,并且可以在/ userid / picture中找到(请参阅https://developers.facebook.com/docs/graph-api/reference/v2.0/user/picture中的 docs和此示例用户: 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! 如果有人想出了一种基于用户名获取个人资料图片的方法,或者选择如何获取用户ID(甚至是替代用户名)来检索个人资料图片,请分享! In the meantime, the old graph url still works until April 2015. 在此期间,旧的图表网址仍然有效,直到2015年4月。

One way is to use the code Gamlet posted in his answer: 一种方法是使用答案中张贴的代码Gamlet

  • Save it as curl.php 将其另存为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; 

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 curl it. 我以为我会发布此信息,因为花了一些时间来弄清细节...即使个人资料照片是公开的,但卷曲时仍需要有访问令牌才能获取。

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

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像素。

I was thinking - maybe ID will be a useful tool. 我在想-也许ID将是一个有用的工具。 Every time a user creates a new account it should get a higher ID. 每次用户创建新帐户时,它都应获得更高的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. 我在Google上搜索后发现,有一种方法可以通过ID估算帐户创建日期,而metadatascience.com上的Massoud Seifi收集了一些有关该数据的良好数据。

在此处输入图片说明

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/

The blog post Grab the Picture of a Facebook Graph Object might offer another form of solution. 博客文章“获取Facebook图形对象的图片”可能提供另一种解决方案。 Use the code in the tutorial along with the Facebook's Graph API and its PHP SDK library. 将教程中的代码与Facebook的Graph API及其PHP SDK库一起使用。

... And try not to use file_get_contents (unless you're ready to face the consequences - see file_get_contents vs curl ). ...并尽量不要使用file_get_contents (除非您准备好面对后果-参见file_get_contents vs curl )。

Are you concerned about the profile picture size? 您担心个人资料图片的大小吗? at the time of implementing login with Facebook using PHP. 在使用PHP实现与Facebook的登录时。 We'll show you the simple way to get large size profile picture in Facebook PHP SDK. 我们将向您展示在Facebook PHP SDK中获取大尺寸个人资料图片的简单方法。 Also, you can get the custom size image of Facebook profile. 此外,您还可以获取Facebook个人资料的自定义尺寸图片。

Set the profile picture dimension by using the following line of code. 通过使用以下代码行来设置个人资料图片尺寸。

$userProfile = $facebook->api('/me?fields=picture.width(400).height(400)'); $ userProfile = $ facebook-> api('/ me?fields = picture.width(400).height(400)');

check this post:http://www.codexworld.com/how-to-guides/get-large-size-profile-picture-in-facebook-php-sdk/ 检查此职位:http://www.codexworld.com/how-to-guides/get-large-size-profile-picture-in-facebook-php-sdk/

@NaturalBornCamper, @NaturalBornCamper,

Nice code! 好的代码! Here is a clean-cut code function for such process! 这是用于此过程的简单代码功能!

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

This will return the raw Facebook avatar image URL. 这将返回原始的 Facebook头像图片URL。 Feel free to do whatever you want with it then! 随便做什么吧!

URI  = https://graph.facebook.com/{}/picture?width=500'.format(uid)

You can get the profile URI via online facebook id finder tool 您可以通过在线Facebook ID查找器工具获取个人资料URI

You can also pass type param with possible values small, normal, large, square. 您还可以传递类型参数,其可能的值包括小,标准,大,平方。

Refer the official documentation 请参阅官方文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我应该怎么获得的Facebook用户的好友列表,并在PHP他们的个人资料图片的使用图形API? - How should i get Facebook user friend list and their profile picture's using Graph API in PHP? Facebook API PHP获取用户的“个人资料图片”相册的ID - Facebook API PHP Get The ID Of User's “Profile Pictures” Album Facebook PHP API如何获取当前用户profile_id? - Facebook PHP API How to get current user profile_id? Facebook PHP SDK - 获取我的应用用户的用户名和个人资料图片,无需Facebook连接 - Facebook PHP SDK - Get user name and profile picture of my app users without requiring facebook connect 通过Facebook API获取用户的生日 - Getting user's birthday through Facebook API 如何在Facebook上获取用户的个人资料图片 - How to get user's profile picture on Facebook 如何在我的 facebook 应用程序中获取用户个人资料中图像的评论框 - How to get comment box of an image in user's profile, into my facebook application Facebook API / PHP - 是否可以通过FB Graph API更改用户的个人资料图像? - Facebook API/PHP - Is it possible to change a user's profile image via FB Graph API? 我无法在Facebook API PHP中获得用户信息 - I cannot get user's informations in facebook api php 建议-来自Facebook Graph API的用户个人资料图片 - Advice - User profile image from Facebook Graph API
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM