Search code examples
phpfacebookphotos

How do get photos of the chosen album in Facebook PHP SDK


This shows the names of the albums as links. When a specific link is chosen the user is being redirected to the albumPhotos.php file. What i need is to put the required code in albumPhotos.php so that the photos of the specific album appear.

$albums = $facebook->api('/me/albums');
Foreach($albums['data'] as $album) 
{
print ('<a href= "albumPhotos.php">'.$album['name'].'</a>'.'</br>' ) ;
}

This is the current code in the apbumPhotos.php. At the time it presents all of the photos of the user.

$albums = $facebook->api('/me/albums');
foreach($albums['data'] as $album)
  {

    $photos = $facebook->api("/{$album['id']}/photos");
    foreach($photos['data'] as $photo)
    {
            echo "<img src='{$photo['source']}' />", "<br />";
    }
 } 

Solution

  • You need to pass which single album you want to the apbumPhotos.php page. Otherwise, your code doesn't know which album link the user clicked on, and it's just looping through all of the user's albums. The logic is pretty simple.

    Use a query string to pass the album_id as $_GET parameter in the link, like so:

    $albums = $facebook->api('/me/albums');
    foreach($albums['data'] as $album)  {
      print ('<a href="albumPhotos.php?album_id='.$album['id'].'">'.$album['name'].'</a>'.'</br>' ) ;
    }
    

    Then, get the album_id parameter in apbumPhotos.php and use it (instead of looping through ALL the albums again, which it is doing now):

    $album_id = $_GET['album_id']; // get the album_id passed in the URL
    $photos = $facebook->api("/{$album_id}/photos"); // just get that one album
    foreach($photos['data'] as $photo)
    {
            echo "<img src='{$photo['source']}' />", "<br />";
    }