After learning how to “create” objects on Facebook (let it be upload an image, create a post or an event) it’s time to learn how to “retrieve” objects from the social graph.

So today, you will learn how to create a simple browser of the user’s Facebook albums. You can have a look at our demo page while you are reading the tutorial.

 

The Requirements

Back to top
 

The Concept

  • We will have a main page index.php where we will be retrieving and listing all the user’s albums in
  • Clicking any of these albums will direct you to the album’s page album.php where we will be listing the photos this time
  • We are going to take care of the paging through query strings
  • Following Facebook’s recommendation, we will be checking for a valid session before making graph api calls
Back to top
 

Our Code

We won’t be listing the whole code in here, but only snippets and comments. You can view the whole project in the “Demo & Source Code” section.

<?php
require '../src/313/facebook.php';
$facebook = new Facebook(array(
	'appId'  => 'APP_ID',
	'secret' => 'APP_SECRET',
	'cookie' => true,
));

$user = $facebook->getUser();
if ($user) {
	try {
		$user_albums = $facebook->api('/me/albums');
		$albums = array();
		if(!empty($user_albums['data'])) {
			foreach($user_albums['data'] as $album) {
				$temp = array();
				$temp['id'] = $album['id'];
				$temp['name'] = $album['name'];
				$temp['thumb'] = "https://graph.facebook.com/{$album['id']}/picture?type=album&access_token={$facebook->getAccessToken()}";
				$temp['count'] = (!empty($album['count'])) ? $album['count']:0;
				if($temp['count']>1 || $temp['count'] == 0)
					$temp['count'] = $temp['count'] . " photos";
				else
					$temp['count'] = $temp['count'] . " photo";
				$albums[] = $temp;
			}
		}
	} catch (FacebookApiException $e) {
		error_log($e);
		var_dump($e);
		$user = null;
	}
}

if ($user) {
	$logoutUrl = $facebook->getLogoutUrl();
} else {
	$loginUrl = $facebook->getLoginUrl(array(
		'scope' => 'user_photos'
	));
}
?>

So here, we are doing the following:

  1. Including the Facebook PHP library
  2. Initialize the Facebook class to start communicating with Facebook
  3. Get the current connected user
  4. If we found one, retrieve the user’s albums and prepare our data array for presentation and our logout link
  5. Otherwise, create the login link with the proper permission

Now for the album page:

<?php
if( !isset($_GET['id']) )
	die("No direct access allowed!");
require '../src/313/facebook.php';
$facebook = new Facebook(array(
	'appId'  => 'APP_ID',
	'secret' => 'APP_SECRET',
	'cookie' => true,
));

$user = $facebook->getUser();
if ($user) {
	try {
		$logoutUrl = $facebook->getLogoutUrl();
		
		$params = array();
		if( isset($_GET['offset']) )
			$params['offset'] = $_GET['offset'];
		if( isset($_GET['limit']) )
			$params['limit'] = $_GET['limit'];
		$params['fields'] = 'name,source,images';
		$params = http_build_query($params, null, '&');
		$album_photos = $facebook->api("/{$_GET['id']}/photos?$params");
		if( isset($album_photos['paging']) ) {
			if( isset($album_photos['paging']['next']) ) {
				$next_url = parse_url($album_photos['paging']['next'], PHP_URL_QUERY) . "&id=" . $_GET['id'];
			}
			if( isset($album_photos['paging']['previous']) ) {
				$pre_url = parse_url($album_photos['paging']['previous'], PHP_URL_QUERY) . "&id=" . $_GET['id'];
			}
		}
		$photos = array();
		if(!empty($album_photos['data'])) {
			foreach($album_photos['data'] as $photo) {
				$temp = array();
				$temp['id'] = $photo['id'];
				$temp['name'] = (isset($photo['name'])) ? $photo['name']:'';
				$temp['picture'] = $photo['images'][1]['source'];
				$temp['source'] = $photo['source'];
				$photos[] = $temp;
			}
		}
	} catch (FacebookApiException $e) {
		error_log($e);
		$user = null;
	}
} else {
	header("Location: index.php");
}
?>
  1. Checking if the page were requested properly
  2. Initialize the Facebook Class and check for a valid user before retrieving the album’s photos
  3. Retrieve the album’s photos with custom offset/limit if applicable
  4. Check for the paging parameters and prepare the paging links if necessary
  5. Prepare the photos array for presentation

The rest of the code should be trivial, where we are building the HTML of the main and albums pages based on the data we’ve collected and organized.

Back to top
 

Demo & Source Code

You can test the application yourself in our demo page or you can download the source code from the link below:

Facebook Albums Browser (1693)

Back to top
  • http://www.facebook.com/people/Benjamin-Smith/661563754 Benjamin Smith

    This is fantastic… Any chance of getting the code required to grant offline access so that it will always display the photos only of 1 user? No login / logout required, just once. :)

  • yanipan

    very interesting, thank you

  • http://www.facebook.com/absolutamentedios Absolutamente Nadie

    thank you men

    your api is very interesting 

  • Stech786

    I downloaded your script as is. Everything works fine, except the “logout” It does not logout user after click “logout” link.

    • http://www.masteringapi.com Ibrahim Faour

      It’s working just fine for me. Is the problem persists?

      • Stech786

        everything works. thanks

  • Phpcore

    Thank you very much for this great tutorial.
    I want to ask for one question : how to make it accessible to visitors, so people who are friends with user or in general who are granted permissions to view user albums can use the application after it was installed by user of course.
    (sorry for my poor English)

  • Anonymous

    thanks.
    your post help me a lot.

  • Guest

    Hi, i have a trouble about paging. Why Graph api give all times this “paging.next” ?

    • http://twitter.com/cocoedu Eduardo Quesquen

      I have the same problem. Can anybody help us please? Thnks.

      • _suB

        Same, did any of you have any luck?

  • Logudotcom

    thanks a lot..

  • Hasulike
  • Rohit

    I downloaded your script as is. Everything works fine, except the “logout” It does not logout user after click “logout” link.

  • http://www.facebook.com/profile.php?id=582932827 Pravin Pindoliya

    absolutely fantastic examples – works very well

  • tha

    Hi,

    I tried your tutorial and demo. Everything works perfectly,except that your code did not retrieve any photos that has been tagged by friends. Do you know how to retrieve photos that are tagged by friends? Thanks

  • Ericjohndelfin

    Do you have a downloadable file of the Demo Page. I just can’t clearly understand, lack of explainations. tnx :D

  • Sami_Salami

    We developed a facebook app showing the user his photo albums as well. We got notice that really a few users saw the page, the albums were loaded on, broken. The stylesheets did not load completely – right the stylesheets! The solution to the problem was even more hilarious! There was no problem with the api calls at all, the problem lies with the variable $user_albums. After renaming it, all problems disappeared, we did not dig far enough yet to say what actually happens or where it comes from, we only know that it has something to do with the facebook php api, so there must be some variable $user_albums in there… and be used in a quite ugly way. Only a little amount of users had these problems, so for them was propably some kind of difference in the called functions and therefore the broken variable $user_albums. We did not figure out the similarity between the users – we could only compare between two and were not able to reproduce it…

    Anyways I strongly recommend to rename $user_albums, because we have tested and are sure that it breaks the page for a few users – saved our day!

    And thanks for the tutorial :-)

    Kind Regards!

  • Renaud

    Thank you this has been useful to me

  • Adil B

    Paging of images and logout does not work.

  • kads

    Hi,

    I need some help. when i am running this code it shows me error. Please try agian later.

  • http://www.facebook.com/people/Sreehari-Kakkad/100000134192713 Sreehari Kakkad

    Everything works fine except logout

  • Madhuri Vaidya

    Firstly thank you for your script, but I am having trouble with permissions. For some reason it is asking only ‘public profile’ permission even though in scope its mentioned ‘user_photos’.
    After login, it does not fetch albums/photos. Please suggest.