Speedwheelftw
Speedwheelftw

Reputation: 393

Facebook - get profile picture php sdk

Until few months ago I was using this method to get the user's facebook profile picture and was working fine.

public function getUserProfilePic(){
   $access_token = $this->facebook_obj->getAccessToken();
   $user_id = $this->facebook_obj->getUser();
   $response = $this->facebook_obj->api(
      "/me/picture",
      "GET",
      array (
        'redirect' => false,
        'type'     => 'large'
      )
   );
   return (!empty($response['data']['url'])) ? $response['data']['url'] : 'images/default_profile.jpg';
}

But since the new PHP SDK I have some problems with this method. If I afk for 5 minutes on the main menu on my app and than go on the click to go the page where it calls this method I get

"OAuthException : An active access token must be used to query information about the current user" error.

Any thoughts?

Upvotes: 3

Views: 9734

Answers (1)

Sahil Mittal
Sahil Mittal

Reputation: 20753

Nothing to do with new/old SDK I guess. The user is logged-out, or access token is expired or your handling of the user in session is flawed.

This error is occurred whenever you try to make calls with /me but no user is logged-in to the app.

So, before making the calls, you should always validate the current user and then proceed, something like that-

$user_id = $this->facebook_obj->getUser();
if ($user_id) {
   try {
       $response = $this->facebook_obj->api(
           "/me/picture",
           "GET",
           array (
               'redirect' => false,
               'type'     => 'large'
           )
       );
   } catch (FacebookApiException $e) {
       error_log($e);
   }
}else {
   // redirect to Facebook login to get a fresh user access_token
   $loginUrl = $this->facebook_obj->getLoginUrl();
   header('Location: ' . $loginUrl);
}

Edit:

You dont need to do redirect: false and fetching the url from the json. You can directly use the url as the image source:

https://graph.facebook.com/{user-id}/picture?type=large

That's it!

Upvotes: 10

Related Questions