Facebook GRAPH API + PHP SDK: get the URL of the large user picture

Alexander Farber picture Alexander Farber · May 6, 2011 · Viewed 12.5k times · Source

I'm trying to rewrite a Facebook app (a PHP script embedding a small multiplayer Flash game) from old FBML to new iFrame type and it kind of works:

<?php

require_once('facebook.php');

define('FB_API_ID', '182820975103876');
define('FB_AUTH_SECRET', 'XXX');

$facebook = new Facebook(array(
            'appId'  => FB_API_ID,
            'secret' => FB_AUTH_SECRET,
            'cookie' => true,
            ));

if (! $facebook->getSession()) {
    printf('<script type="text/javascript">top.location.href="%s";</script>',
        $facebook->getLoginUrl(
                array('canvas'    => 1,
                      'fbconnect' => 0,
                      #'req_perms' => 'user_location',
        )));

} else {
    try {
        $me = $facebook->api('/me');

        $first_name = $me['first_name'];
        $city       = $me['location']['name'];
        $female     = ($me['gender'] != 'male');
        $fields     = $facebook->api('/me', array(
                          'fields' => 'picture',
                          'type'   => 'large'
                      ));
        $avatar     = $fields['picture'];

        # then I print swf tag and pass first_name;city;avatar to it

    } catch (FacebookApiException $e) {
        print('Error: ' . $e);
    }
}

?>

but I think that the call to get the user profile picture causes my script to perform a 2nd CURL fetch, which is probably avoidable? And also I'd like to use the new GRAPH API and not the old REST API - but I'm not sure how to rewrite that call (and I need to get the large and direct user picture).

Answer

Jimmy Sawczuk picture Jimmy Sawczuk · May 6, 2011

If you know the user ID, just use:

<img src="http://graph.facebook.com/<UID>/picture?type=large" />

Also note that you can use that URL to retrieve the contents via cURL. If necessary, you can also use cURL to follow the redirects and get the final URL.

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, 
    "http://graph.facebook.com/<UID>/picture?type=large");

curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_exec($ch);

$url = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);

curl_close($ch);

var_dump($url);