Create photo albums and upload photos using the Facebook Graph API

By David Pratt / Tags: , / 71 Comments / Published: 11-09-10

UPDATE: Thanks to some of the comments below I have been able to revise the code – thanks Luke & Guilherme

I thought I’d share some recent learning’s with using the Facebook Graph API as there seems to be so few examples out there about how to utilise various aspects of its functionality. I will explain how to create a photo album and then insert a photo into it using PHP.

The code example assumes that you have already generated an authenticated session and have the correct permissions (read_stream, publish_stream, photo_upload, user_photos, user_photo_video_tags). If you haven’t already done so, then there is a good example here about how to do so and you can read more about the Facebook permissions on the Facebook dev site.

The following snippet creates a photo album and then uploads a photo into it:

//At the time of writing it is necessary to enable upload support in the Facebook SDK, you do this with the line:
$facebook->setFileUploadSupport(true);
 
//Create an album
$album_details = array(
		'message'=> 'Album desc',
		'name'=> 'Album name'
);
$create_album = $facebook->api('/me/albums', 'post', $album_details);
 
//Get album ID of the album you've just created
$album_uid = $create_album['id'];
 
//Upload a photo to album of ID...
$photo_details = array(
	'message'=> 'Photo message'
);
$file='app.jpg'; //Example image file
$photo_details['image'] = '@' . realpath($file);
 
$upload_photo = $facebook->api('/'.$album_uid.'/photos', 'post', $photo_details);

You can add more detail to the created album and photo than I have in the example by using additional parameters within the arguments array.

Category: Tech

Tags: ,

Posted: on September 11th, 2010 at 6:08 pm.

Feeds: RSS 2.0

71 Responses to “Create photo albums and upload photos using the Facebook Graph API”

Anna September 26th, 2010 at 1:43 am

Works great, thanks!
Spent 2 days trying to figure out how to upload a photo and couldn’t find any decent examples until I came across this.
(Turns out my problem was that I needed to enable uploads with setFileUploadSupport but this is the first example I found it in so THANK YOU!)

David Pratt September 26th, 2010 at 2:04 am

Yer that setFileUploadSupport caused me no amount of head scratching!

vhw October 7th, 2010 at 9:50 pm

thank you! your example was really helpful and it saved me a ton of time :)

Kaspar October 19th, 2010 at 12:18 pm

Hi

Great example. I have a question, in case anybody knows the answer. I’m trying to publish stright into my application’s page. I want to perform, via Graph api or Php SDK, the same action you do when uploading and sharing an album. The thing is that i don’t know if i can do that, but when i try to create an album passing access token and album details, the api creates it into my personal album’s page, not in my application’s page.

I dont know if I made myself clear enough. Any help would be appreciated!

falcon November 24th, 2010 at 12:48 pm

Any comment if using C#, i am stuck on the error: 324, requires upload files.

Aldes November 24th, 2010 at 6:49 pm

Can you help me.
$albums = $facebook->api(‘/me/albums’);
This string is returned empty array to me.
Array
(
[data] => Array()
)
All the code works except for this moment.

szataniol November 27th, 2010 at 6:36 pm

@falcon – you need to init facebook client with additional parameter fileUpload = true

David December 5th, 2010 at 10:58 pm

Same problem as @aldes, would be more than grateful if somebody would know what’s happening…

David December 5th, 2010 at 11:03 pm

Wow, after searching for 2 hours or so I wrote the comment and 2 minutes later I found out it was a permissions problem (forgot to re-add my app with the extended permissions). so @aldes, make sure you have all the required permissions

Shawn Adrian December 24th, 2010 at 1:18 am

Wow man, bonus points for this. I had it working first try!

manujapanday December 31st, 2010 at 12:31 pm

Wow ….. Great tutorial. Can you help me on tagging a uploaded photo. Thanks

falcon January 7th, 2011 at 5:58 am

Hi, szataniol, i’m using desktop authentication, just using an access_token to work it. Also, i’m using github sdk for C#. It does have any params for me to do this setting.

Pratigya January 10th, 2011 at 3:17 pm

i am facing problem to upload image in .net.Plz if possible so provide this code in C#.Net

robochimp January 16th, 2011 at 9:11 pm

Is it possible to use a php file that creates an image as the file source?

$file=’app.php’; //Example image file
$photo_details['image'] = ‘@’ . realpath($file);

Luke Dyson January 22nd, 2011 at 4:50 pm

You can replace:

//Get album ID of the album you’ve just created – there could well be a cleaner way of doing this.
$albums = $facebook->api(‘/me/albums’);
foreach ($albums[data] as $album) {
//Test if the current album name is the one that has just been created
if($album[name] == ‘Album name’){
$album_uid = $album[id];
}
}

With just:

$album_uid = $create_album['id'];

Guilherme Cardoso January 30th, 2011 at 7:34 pm

Luke is right.
The “$facebook->api(‘/me/albums’, ‘post’, $album_details);” will return you the new album created, so you can check the Id from there.
In fact, the $create_album contains all album information (create time, updatetime, owner, etc).

Sebastian January 31st, 2011 at 12:40 am

thanks for this, first decent example code i found =)

Ben February 3rd, 2011 at 7:39 pm

Hi,

Having trouble with the returned data:
$album_uid = $create_album['id'];

This is coming through as a float?
float(1.944109172517E+14)

Anybody else getting this issue; found a solution?

Thanks.

cherijs February 4th, 2011 at 1:35 pm

you make so much new albums, with same name :)

foreach ($albums[data] as $album) {
//Test if the current album name is already in facebook
if($album[name] == ‘Wufff’){
$album_uid = $album[id];
}
}

if(!$album_uid){
//album dosn’t exist, so wee need to create one
$create_album = $facebook->api(‘/me/albums’, ‘post’, $album_details);
$album_uid = $create_album['id'];
}

johndhuk February 5th, 2011 at 3:26 pm

Helpful article. As has been pointed out above however, it creates a new album with the same name on every run.

Instead of a foreach to find an existing album, we can use the very powerful and easy FQL to also check that the album can be uploaded to (e.g. is not full):

$album = $facebook->api(array(
‘query’ => ‘SELECT object_id FROM album WHERE owner=me() AND name=’Album name’ AND can_upload=1′,
‘method’ => ‘fql.query’
));

if (isset($album[0]['object_id'])) $album_uid = $album[0]['object_id'];
else
{
// No valid album exists, create new album here
}

David Pratt February 7th, 2011 at 10:26 pm

Code example updated… cheers Luke & Guilherme! I like your approach johndhuk as well.

juan zapata February 11th, 2011 at 6:29 am

thanks mate very helpful

juan zapata February 11th, 2011 at 6:32 am

great blog, save me hours of scratching my head

Manju February 12th, 2011 at 8:30 pm

thanks a ton dude. it helped me a lot. keep blogging as it helps a millions of developers who mainly depends on google for app developements :D

Syed Sumair Zafar February 24th, 2011 at 1:13 pm

@johndhuk

but fql and facebook => api
both give different aid of album

and also i from Facebook =>api i am getting only latest 24 albums not all of the album

can anyone experienced this scenario?

tousif March 1st, 2011 at 5:57 am

hey I did this task and its working but now i need to getback the id of uploaded image in a variable how do i perform this?

robin March 2nd, 2011 at 6:01 am

Need some help.
I need to let user upload a photo from their local drive then grab the file and add into their album.
index.php:

Choose a file to upload:

uploader.php
$target_path = “uploads/”;
$target_path = $target_path . basename( $_FILES['uploadedfile']['name']);
echo $target_path . “”;

if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
echo “The file “. basename( $_FILES['uploadedfile']['name']).
” has been uploaded” . “”;
} else{
echo “There was an error uploading the file, please try again!” . “”;
}

and with the codes you shared with us. my application does not work. Whenever i submit the form, it jumps to uploader.php. It runs for awhile then reloads itself and all the data sent by the html form are gone.

Please help

Jorge March 4th, 2011 at 11:31 pm

Help please

$create_album = $facebook->api(‘/me/albums’, ‘post’, $album_details);

=

Error:SSL certificate problem, verify that the CA cert is OK. Details: error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed

Manish March 16th, 2011 at 9:53 am

Thanks a lot man..It helped me alot :)

MrBeau April 1st, 2011 at 1:45 am

I was getting some IDs returned as floats. I fixed it by setting the precision:

$precision = 25;
ini_set(“precision”, $precision);

Dean Erling April 17th, 2011 at 11:17 pm

These examples don’t work when the image source is a URL. WHY??????????????????????

dbKooper April 18th, 2011 at 9:55 pm

Hi,
I have coded to upload picture using jquery/ajax;plz help;
following is dump of response error:
curlException occuring:
[message:protected] => failed creating formpost data
[string:private] =>
[code:protected] => 26
[line:protected] => 639
[trace:private] => Array
(
[0] => Array
(
[file] => /home/*******/public_html/******/facebook.php
[line] => 592
[function] => makeRequest
[class] => Facebook
[type] => ->
[args] => Array
(
[0] => https://graph.facebook.com/me/photos
[1] => Array
(
[access_token] => 198912270135350|2.3fAdZTAGWRN673kFzvMMAA__.3600.1303160400.1-100002093628619|jrAew4QmVctmu6zSQU_Bf-3sBBs
[source] => @
[name] => ******
[message] => ******
[method] => POST
)

)

)

[1] => Array
(

[file] => /home/*******/public_html/******/facebook.php
[line] => 592
[function] => makeRequest
[class] => Facebook
[type] => ->
[args] => Array
(
[0] => https://graph.facebook.com/me/photos
[1] => Array
(
[access_token] => 198912270135350|2.3fAdZTAGWRN673kFzvMMAA__.3600.1303160400.1-100002093628619|jrAew4QmVctmu6zSQU_Bf-3sBBs
[source] => @
[name] => ******
[message] => ******
[method] => POST
)
)

)

[2] => Array
(

[file] => /home/*******/public_html/******/facebook.php
[line] => 592
[function] => makeRequest
[class] => Facebook
[type] => ->
[args] => Array
(
[0] => https://graph.facebook.com/me/photos
[1] => Array
(
[access_token] => 198912270135350|2.3fAdZTAGWRN673kFzvMMAA__.3600.1303160400.1-100002093628619|jrAew4QmVctmu6zSQU_Bf-3sBBs
[source] => @
[name] => ******
[message] => ******
[method] => POST
)

)

)

LK Patir May 17th, 2011 at 1:46 pm

This is good, specially thank you for the code line $facebook->setFileUploadSupport(true);

Sourav June 7th, 2011 at 4:20 am

I got this ERROR !
Fatal error: Uncaught CurlException: 26: failed creating formpost data thrown in facebook.php on line 589

gasgas June 8th, 2011 at 9:34 am

This could be a useful implementation: http://www.gleenk.com/personalizzare-foto-profilo-facebook-api/
I don’t know italian but the code it’s self explained. I’ve found it really interesting and i’ve already used it as service for my clients and facebook marketing proposal

papawix June 9th, 2011 at 4:54 am

hi guys… i need your help… I copied and tried to execute the given codes above.. and I got this errors:

Notice: Undefined variable: facebook in C:\projects\xampp\htdocs\DSLR\create_album.php on line 3

Fatal error: Call to a member function setFileUploadSupport() on a non-object in C:\projects\xampp\htdocs\DSLR\create_album.php on line 3

can you help me fix this??? or is there something I need to download??

what I want to do it that. I want to create an album and upload pictures automatically to facebook after it was taken from a camera.

Mongsangga June 12th, 2011 at 5:08 pm

can this be done with FB.api function?

Raja Sekhar Upputuri June 16th, 2011 at 5:19 pm

I am new to facebook apps development. I tried the code above but it keeps on refreshing. I first validated the user using fbmain.php and then in index.php i had just pasted this code. Is this how this should be developed?.

Thank You

SHaun June 30th, 2011 at 7:38 am

Raja Sekhar Upputuri did you get it to work im haveing same problem

Raja Sekhar Upputuri July 1st, 2011 at 5:31 am

@Shaun,
It is working well now. I am able to upload images. But every time it is creating a new album. I tried Johndhuk’s code. But even if the album is present, it is returning NULL value for album id.

Marcos Lavorato August 2nd, 2011 at 5:27 am

Huge thanks man. Works very well!

haxpor August 28th, 2011 at 9:19 pm

FYI:
I found out that the id shown on the url bar in browser (the first section) is the object_id, and not aid.
I successfully checked this after execute fql command checking equality between object_id and the section mentioned manually copied from url bar.

haxpor August 28th, 2011 at 9:21 pm

In addition, one thing which is very important is that remember to include “user_photos” in your permission for the app as well. It needs that in order to do fql query and checking against its properties of a table.

Tom September 2nd, 2011 at 11:06 am

Hello Guys,
I got following error

Fatal error: Call to a member function setFileUploadSupport() on a non-object in /home6/groovepi/public_html/demo/fb/index.php on line 25

App canvas url is http://apps.facebook.com/novauploader/

Could anybody help me with that or just send me the zipped source of the tutorial ?

I will be thankfull

sivamurugan September 5th, 2011 at 9:58 am

Can any one tell how to use the same in Iphone SDk

fck September 21st, 2011 at 5:57 am

If it works, THANKS A LOT

Guilherme Cardoso September 24th, 2011 at 2:28 am

You’re welcome mate.
On the next days i’ll write a few articles about facebook integration with .NET using Facebook C# SDK (i wrote it a few months ago but for version 4) and Facebook Graph API.

Feel free to check my blog ;)

Dido September 29th, 2011 at 6:58 am

Hi David,

Thank you so much for this code. I’ve been working with it since last year but now FB will retire PHP SDK 2.0 and requires SDK 3.0 which your current code needs to be edited to work with it. Are you planning to update your current code soon? Facebook will stop work with PHP SDK 2.0 from 1 Oct 2011 (less than two days from now).

Thanks again for your help and I do appreciate the time you put in this code.

Lee October 14th, 2011 at 9:01 pm

Hi, thanks for your help. I think this code doesn’t work now though with the updated Facebook API. Can you please update this so it becomes compatible with the new API? Thanks!

Phuc October 22nd, 2011 at 12:10 pm

The code work fine with facebook profile and profile album but I am on way to try to upload to my facebook fan page, any idea for this? I used album id from fan page for album id but it doesn’t help.

Hardrock November 1st, 2011 at 10:23 am

pls upadte the code

Arvind Bhardwaj November 6th, 2011 at 9:31 am

Hi,
Its a nice article.
I have also written an article for uploading photos on Facebook photo album. You can try it here:http://www.webspeaks.in/2011/08/upload-photos-on-facebook-using-php.html

Ritika November 7th, 2011 at 12:11 pm

hy please send me copmlete tutorial on how to upload pic on facebook

Karan Adep November 24th, 2011 at 9:46 am

Great and simplified tutorial , thanks a ton

Gandhar January 16th, 2012 at 8:19 am

how can i create an album in a group?

I get the following error when I try to create an album in a group
(#10) Application does not have permission for this action

Following is my code:-
$facebook = new Facebook(array(
‘appId’ => APP_ID,
‘secret’ => SECRET_ID,
‘cookie’ => true
));
$loginUrl = $facebook->getLoginUrl( array(‘scope’ => ‘read_stream,publish_stream,photo_upload,user_photos, user_photo_video_tags,user_groups,offline_access’));
$album_details = array(
‘message’=> ‘Test Album from api’,
‘name’=> ‘Test Album’
);
$create_album = $facebook->api(GROUP_ID.’/albums’, ‘post’, $album_details);

Angelo January 21st, 2012 at 11:14 pm

So helpfull, thanks a lot guy !

Keith Lantz January 31st, 2012 at 6:53 pm

Any updates on Gandhar’s issue? We receive the same error when attempting to create an album within a group.

Adiraz February 6th, 2012 at 9:33 am

hey friends..i can creating an album though php code.but i can’t upload a image in album. anybody here who can help me.

so please i request his/her contact me on fb.

http://facebook.com/adiraz786
http://facebook.com/adirazrocks

Thanks In advanced

Sam March 30th, 2012 at 10:44 pm

+1 on Gandhar’s issue, this just started happening for no reason in my application.

ignacio April 15th, 2012 at 11:00 pm

i am sorry for the foolish question, but when I must place this .php code? And from where is it called?

naveed khan April 17th, 2012 at 3:16 pm

Thanks its work fine, thanks a lot for your great support..

Sky July 30th, 2012 at 12:18 pm

Hey guys. Need help urgently. For this app function of photo uploading, should i set query string or URI Fragment for the Auth Token Parameter?

nazir September 1st, 2012 at 6:42 am

thanks a lot, you save my life, thank you

ashish September 5th, 2012 at 6:31 pm

Hi, Nice tutorial. Just out of curosity, Can we upload photos/videos in past date ?

arth September 27th, 2012 at 8:58 am

if i want to upload photo to page created by me then..??

please give me right solution

Sébastien November 14th, 2012 at 2:50 am

Why i got this error ??

Uncaught OAuthException: (#100) Invalid ID for album owner thrown

jay December 31st, 2012 at 11:50 am

Fatal error: Uncaught OAuthException: An active access token must be used to query information about the current user. thrown in D:\wamp\www\fb\facebook\examples\base_facebook.php on line 1239

Robert January 6th, 2013 at 3:50 pm

Hi, I’m getting this error:

Fatal error: Uncaught CurlException: 26: failed creating formpost data thrown in base_facebook.php on line 972

Can anyone help please?

Thanks,

Robert

DonDinh May 6th, 2014 at 3:56 am

Hello, Any updates on Gandhar’s issue? I got the same issue.
Please help me
Thanks a lot

Leave a reply