Facebook Page Photo Gallery Using Facebook API

2016-01-11

If you want to build use Facebook's Open Graph API to build a Photo Gallery for a page (any public page, you don't even have to manage it), then follow these steps.

See the working example / demo

Download the Source Code

Why?

I was in the process of changing my hosting from Hostagators Shared Hosting to Digital Ocean's VPS. As I was transferring over the files I realised I'd need to transfer all of the photos one of my clients uploaded to the server, over to the new server. This was bad, because there was over 10GB of photos, which I hadn't compressed properly, and that would have eaten up over half of my 20GB SSD with Digital Ocean. Of course there were / are other solutions but I decided this one was the best for the following reaons

  • Hosting Images is eventually going to be expensive when you're uploading hundreds weekly
  • The Gallery system on the existing site was SLOW and mostly broken, so it needed to be re-done anyway.
  • My client was uploading his photos to Facebook anyway, and they have a much nicer interface than I could ever have written.

So that's the why, let's get down to the how.

How?

  • Using just a Facebook (FB) page id, you can get a JSON formatted result of all the albums a page has publicly listed (more)
  • From there you can get the Album Name, the Cover Photo and (more)
  • From there you can get high-res and low-res copies of each image in thre album (more)

To get started, create a new text file index.php

We are going to be loading the albums dynamically with an AJAX request so make a Javascript Function getAlbums()

<script type="text/javascript"></p> // Makes An AJAX Request On Load which retrieves the albums function getAlbums() { $.ajax({ type: 'post', url: 'scripts/loadGallery.php', data: { }, success: function( data ) { //Hide The Spinner document.getElementById("spinner").style.display = "none"; //Put the Data in the Div document.getElementById("galleryDiv").innerHTML = data; } }); } </script>

Then in the openingbodytag, callgetAlbumson load

<body onload="getAlbums(')">

Create a new file calledloadGallery.phpin thescripts/directory.

In this file you need to 4 do things

  1. Include your FB App Details (I'll cover this in a minute)
  2. Create a function to make the Facebook GETrequest
  3. Get the Albums for the given Page
  4. Process thos Albums and Get Their Cover Photos

Create a new text file calledconfig.txtin that file include the following

<?php $fb_page_id = "##############"; $access_token = "#############|#######################";</p> <p> $albums_per_page = 12; $pics_per_page = 16;</p> <p> $show_all = FALSE; //Set to TRUE to show Timelime Photos, Cover Photos & Profile Pictures ?>

As I said above, we'll find and fill in these details later.

Next, go back toloadGallery.phpand incude that configuration file as follows:

<?php include('../config.txt');</p> ...

Include a function calledcurl_get_contents($url)which will return the content of any url we pass into it.

<?php include('../config.txt');</p> function curl_get_contents($url) { $ch = curl_init($url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); $data = curl_exec($ch); curl_close($ch); return $data; } ...

Next, we need to outline the fields which we want the FB API to return

$fields = "id,count,cover_photo,created_time,description,link,name";

And the link which will return the albums

$json_link = "https://graph.facebook.com/{$fb_page_id}/albums/?access_token={$access_token};

Now, get the returned data, decode it, and loop through each album

$json = json_decode(curl_get_contents($json_link)); $count = 0; for($i=1; $i<= sizeof($json->data) ; $i++): $album = $json->data[$i-1]; //var_dump($album); if(isset($album->cover_photo) && (($album->name != "Cover Photos" && $album->name != "Profile Pictures" && $album->name != "Timeline Photos" ) || $show_all)):</p> $fields="id,height,images,width,link,name,picture"; $album_link = "https://graph.facebook.com/{$album->cover_photo->id}/?access_token={$access_token}&fields={$fields}"; $album_json = json_decode(curl_get_contents($album_link)); //var_dump($album_json); if(isset($album_json->images[3]->source)){ $cover_ind = 3; $cover = $album_json->images[$cover_ind]->source; } else { $cover_ind = 0; $cover = $album_json->images[0]->source; } if($album_json->images[$cover_ind]->height < $album_json->images[$cover_ind]->width){ $orientation = "landscape"; } else{ $orientation = "portrait"; } $count++; ?> <div className="col-sm-5 col-sm-offset-1 col-md-offset-0 col-md-3 album-cover"> <div className="portfolio-item"> <a href="album.php?id=<?php echo $album->id ?>"> <img className="img-responsive <?php echo $orientation;?>" src="<?php echo $cover; ?>" alt="<?php echo $album->name; ?>"> </a> </div> <div className="img-label"><?php echo $album->name; ?></div> </div> <?php if($count%4 == 0) : ?> </div> <div className="row"> <?php endif;?> <?php endif;?> <?php endfor; ?> </div> <!-- End of Row -->

This will output all of the Album images and their titles, in a Bootstrap-ready layout.

Clicking on Any of the Album Covers should bring you to a new page called album.phpso go ahead and create that new file, it's very similar to the previous steps so I won't repeat much

As before you'll want to include your config files and yourCURLfunction, so that we can get the album Title (and date if you so wished) on the Album Page

<?php include('config.txt');</p> // CURL Function which gets the data from FB function curl_get_contents($url) { $ch = curl_init($url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); $data = curl_exec($ch); curl_close($ch); return $data; }

Next we need to get the IDof the album, which we passed through with it in the URL.

If the ID variable exists, we get the name etc, otherwise we kill the page (or redirect to an error page)

// If the Album ID is set in the URL, get it and get the data from facebook if(isset($_GET['id'])){ $fields = "count,created_time,description,link,name"; $id = $_GET['id']; $json_link = "https://graph.facebook.com/".$_GET['id']."/?access_token={$access_token}&fields={$fields}"; $album = json_decode(curl_get_contents($json_link)); } else { // If there's no ID set, DIE die(); }

Once again, in the Head of the HTML Document, we will have an AJAX call that is called onload

$.ajax({ type: 'post', url: 'scripts/loadAlbum.php', data: { id: '<?php echo $id;?>', album_name: '<?php echo $album->name;?>' }, success: function( data ) { document.getElementById("spinner").style.display = "none"; document.getElementById("galleryDiv").innerHTML = data; } }); </script> <body onload="getAlbum()"> ... <!-- Page Content --> <div className="container"></p> <!-- Page Heading --> <div className="row" > <div className="col-lg-12"> <h1 className="page-header"><?php echo $album->name; ?> <a href="index.php"><small>Gallery</small></a> </h1> </div> </div> <!-- Projects Row --> <div id="galleryDiv"> <div className="row"> <div className="col-xs-2 col-xs-offset-5" id="spinner"> <div className="loader" >Loading Albums...</div> </div> </div> <!--End Row --></p> </div> </div> ...

Create a new fileloadAlbum.phpin thescripts/directory

This file is very similar to before inloadGallery.php

  1. Include the Configuration File
  2. Get The album ID & The Album Name from the POST
  3. Create theCURLfunction
  4. Get The photos in the Album
  5. Get Each Image in Hi-Res and Low-Res and display them in the gallery
<?php include('../config.txt');</p> $id = $_POST['id']; $extra_params = $_POST['extra_params'] . "&limit=" . $pics_per_page; $album_name= $_POST['album_name'];</p> function curl_get_contents($url) { $ch = curl_init($url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); $data = curl_exec($ch); curl_close($ch); return $data; } // Get Album Photos // $fields = "id,count,cover_photo,created_time,description,link,name"; $json_link = "https://graph.facebook.com/{$id}/photos/?access_token={$access_token}". $extra_params; // echo $json_link; $json = json_decode(curl_get_contents($json_link)); $count = 0; for($i=1; $i<= sizeof($json->data) ; $i++): $photo = $json->data[$i-1]; $fields="id,height,images,width,link,name,picture"; $album_link = "https://graph.facebook.com/{$photo->id}/?access_token={$access_token}&fields={$fields}"; $album_json = json_decode(curl_get_contents($album_link)); if(isset($album_json->images[4]->source)) { $cover_ind = 4; $pic = $album_json->images[$cover_ind]->source; } else { $cover_ind = 0; $pic = $album_json->images[0]->source; } if($album_json->images[$cover_ind]->height < $album_json->images[$cover_ind]->width) { $orientation = "landscape"; } else{ $orientation = "portrait"; } if(isset($album_json->images[1])) { $large = $album_json->images[1]->source; } else { $large = $album_json->images[0]->source; } $count++; ?> <div className="col-xs-10 col-xs-offset-1 col-sm-5 col-sm-offset-1 col-md-offset-0 col-md-3 album-cover" > <a href="<?php echo $pic; ?>" data-toggle="lightbox" data-title="<?php echo $count ."/". sizeof($json->data) . " ".$album_name; ?>" data-footer="FB API Gallery - Created By <a href='darraghmckay.com' target='_blank'>Darragh Mc Kay</a>" data-gallery="popupgallery"> <div className="portfolio-item"> <img className="img-responsive <?php echo $orientation;?>" src="<?php echo $pic; ?>" > </div> </a> </div> <?php if($count%4 == 0) : ?> </div> <div className="row"> <?php endif;?> <?php endfor; ?></p>

That should be enough to get your started.

The full working demo can be seen here

The Code is available to Download on My github here

The Repository contains instruction on how to set up the example and how to obtain a FB App ID and a FB App Secret.

The working examplel (and the Github Repo) also contains extra features such as:

  • a Loading 'Spinnner'
  • A working Lightbox
  • Pagination, so you can limit how many pictures / albums are downloaded

I hope this tutorial has helped you set up a Facebook Photo Gallery like it did for me. If you have any questions please just send me an email using the form below.