Thursday, January 6, 2022

[FIXED] Get Profile Picture url from Facebook API - PHP SDK V.5

Issue

I want to get the profile's picture url. To get the name I do the following:

$fb = new \Facebook\Facebook([
      'app_id' => '{app_id}',
      'app_secret' => '{app_secret}',
      'default_graph_version' => 'v2.5',
      'default_access_token' => '{access_token}', 
]);

$response = $fb->get('/me');

$name = $response->getGraphObject()->asArray();

$name = $name['name'];
echo $name;

With the same logic I tried to get the profile picture url with the following:

$fb = new \Facebook\Facebook([
      'app_id' => '{app_id}',
      'app_secret' => '{app_secret}',
      'default_graph_version' => 'v2.5',
      'default_access_token' => '{access_token}', 
]);

$response = $fb->get('/me/picture');

$pic = $response->getGraphObject()->asArray();

$pic = $pic['url'];
echo $pic;

And it didn't work. From the graph explorer I know that what I am getting when I am calling the /me/picture which is this:

   {
       "data": {
           "is_silhouette": false,
           "url": "https://scontent.xx.fbcdn.net/ etc etc "
       }
   }

So I am sure that I am making the right call but I mess it up when I am trying to get the url. My thinking is am going to the data object but I can't get the url value. I also tried with the get field, but had no luck:

   $pic = $response->getGraphObject()->asArray();
   $pic->getField('url');

Removing the ->asArray() made no difference. Lastly I tried it this way but again no luck.

  $object = $response->getGraphObject();
  $pic = $object->asArray('data');
  $pic = $pic['url'];
  echo $pic;

Any help would be appreciated :)


Solution

So basically I discovered that there is a function called getGraphUser.

       $response = $fb->get('/me?fields=picture');
       $user = $response->getGraphUser();
       $name = $user->getPicture();
       echo $name['url'];


Answered By - Alex Spyr

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.