简体   繁体   中英

Get facebook user's profile picture

This is my php code to get Facebook user profile image when I have logged in using facebook in my website. But photos is not displaying. I am getting a broken image.

<?php
session_start();

require_once 'vendor/autoload.php';

Facebook\FacebookSession::setDefaultApplication('appid', 'appcode');
$facebook = new Facebook\FacebookRedirectLoginHelper('http://example.com/index.php/');


try 
{
    if($session = $facebook->getSessionFromRedirect()) 
    {
        $_SESSION['facebook'] = $session->getToken();
        header('Location: ../index.php');
    }
    if(isset($_SESSION['facebook'])) 
   {
        $session = new Facebook\FacebookSession($_SESSION['facebook']);
        $request = new Facebook\FacebookRequest($session, 'GET', '/me');
        $request = $request->execute();
        $user = $request->getGraphObject(Facebook\GraphUser::className());
        echo "Name: " . $user->getName();
        echo "<br/>";

        echo '<img src=\"https://graph.facebook.com/". $user. /picture?type=large\">';

    }
}

    catch(Facebook\FacebookRequestException $e) 
    {

      echo " Error: " . $e->getMessage();
    }  
    catch(\Exception $e) 
      {

      }
?>

Simply use the following Graph path via GET request:

/{user_id}?fields=picture.type(large),id,name

Field type can be one of the following values:

  • small
  • normal
  • large
  • square

Or using width and/or height value like this:

/{user_id}?fields=picture.width(200).height(200),id,name

Also you can add redirect=0 param. By default the picture edge will return a picture instead of a JSON response. If you want the picture edge to return JSON that describes the image set redirect=0 when you make the request.

So you will have JSON response:

{
  "picture": {
    "data": {
      "height": 120,
      "is_silhouette": false,
      "url": "https://scontent.xx.fbcdn.net/hprofile-xaf1/v/t1.0-1/c53.10.120.120/165675_138088076251005_752993_n.jpg?oh=a9450bf53f2d2294531e11ae28be99c1&oe=56C740A5",
      "width": 120
    }
  },
  "id": "138087416251071",
  "name": "Zenonis",
}

If you set up a Facebook app, you have an "App ID" and an "App Secret" (which you specify as 'ID' and 'Code').

You can use both these variables to get a user's picture with the following url:

$url = 'https://graph.facebook.com/v2.0/' . $user_id . '/picture?redirect=0&type=large&access_token=' . $app_id . '|' . $app_secret;

You can then print this url out in an src attribute:

<img src="<?php print $url; ?>" />

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM