Upload photos to Facebook Fan Page using PHP

90 comments
After writing the article on Uploading photos to Facebook albums, I though it would be a good idea to tell my readers how to upload photos to your Facebook fan page. Uploading photos to the fan page is a bit different from uploading photos to your album. Here we need the access token of your Fan page. If you know the id of your Fan page, it can be found on runtime though. So here is the script to upload the pics.


Live Demo Download Script
PHP Code:
<html>
<head>
<title>WebSpeaks.in | Upload images to Facebook</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head>

<body>
<?php
require_once 'library/facebook.php';
$facebook = new Facebook(array(
 'appId'  => $app_id,,
 'secret' => $app_secret,
 'fileUpload' => true
));


//It can be found at https://developers.facebook.com/tools/access_token/
$access_token = '<Your access token>';

$params = array('access_token' => $access_token);

//The id of the fanpage
$fanpage = '330299184793';

//The id of the album
$album_id ='10150418901414794';

//Replace arvind07 with your Facebook ID
$accounts = $facebook->api('/arvind07/accounts', 'GET', $params);

foreach($accounts['data'] as $account) {
 if( $account['id'] == $fanpage || $account['name'] == $fanpage ){
  $fanpage_token = $account['access_token'];
 }
}


$valid_files = array('image/jpeg', 'image/png', 'image/gif');

if(isset($_FILES) && !empty($_FILES)){
 if( !in_array($_FILES['pic']['type'], $valid_files ) ){
  echo 'Only jpg, png and gif image types are supported!';
 }else{
  #Upload photo here
  $img = realpath($_FILES["pic"]["tmp_name"]);

  $args = array(
   'message' => 'This photo was uploaded via WebSpeaks.in',
   'image' => '@' . $img,
   'aid' => $album_id,
   'no_story' => 1,
   'access_token' => $fanpage_token
  );

  $photo = $facebook->api($album_id . '/photos', 'post', $args);
  if( is_array( $photo ) && !empty( $photo['id'] ) ){
   echo '<p><a target="_blank" href="http://www.facebook.com/photo.php?fbid='.$photo['id'].'">Click here to watch this photo on Facebook.</a></p>';
  }
 }
}

?>
 <!-- Form for uploading the photo -->
 <div class="main">
  <p>Select a photo to upload on Facebook Fan Page</p>
  <form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" enctype="multipart/form-data">
  <p>Select the image: <input type="file" name="pic" /></p>
  <p><input class="post_but" type="submit" value="Upload to my album" /></p>
  </form>
 </div>
</body>
</html>

A bit of CSS:
html{
 font-family: "lucida grande",tahoma,verdana,arial,sans-serif;
}
.main{
 width:400px;
 margin:auto;
 border:2px solid #0066CC;
 color:#3B5998;
 padding:20px;
 font-size: 11px;
    -moz-border-radius: 4px 4px 4px 4px;
    border-radius: 4px 4px 4px 4px;
    -moz-box-shadow: 1px 1px 0 #d5d5d5;
 background: none repeat scroll 0 0 #F2F2F2;
}
.text{
 color: #777777;
 border: 1px solid #BDC7D8;
 font-size: 11px;
 height: 15px;
}
.post_but {
    background: none repeat scroll 0 0 #EEEEEE;
    border-color: #999999 #999999 #888888;
    border-style: solid;
    border-width: 1px;
    color: #333333;
    cursor: pointer;
    display: inline-block;
    font-size: 11px;
    font-weight: bold;
    padding: 2px 6px;
    text-align: center;
    text-decoration: none;
}
a{
 color:#3B5998;
}

90 comments

I tried this code with my own app, filled in my id / account /secret key etc. But $accounts = $facebook->api('/MYUSERNAMEHERE/accounts', 'GET', $params); always returns an empty array. What could be wrong. i would be sooo happy if you reply to this cause i did not find a single working example of it beside your live demo. thanks in advance!

Im also the Admin of the Page where i want to post the picture in the album. I think i am missing something simple, but cant figure it out for hours now :(

Hi Stefen,
I believe you may be missing the right access token for the page. The token can be found at It can be found at https://developers.facebook.com/tools/access_token/. Please try with it.

Thanks.

Glad you found time to answer. I managed to fix the error with the empty array by granting "manage_pages" permissions for my app. But im wondering how YOU did that. As far as i can see in your live demo there is not a single facebook dialog for the user to accept. And thats the thing thats very important for me. I have to use this script for users (which are not admins of the fanpage) they can draw a picture. This picture is supposed to be posted in an album on the fanpage. As i am am saving the script successfully on my server via php it would be wonderful to automatically move it to the album. So im wondering how you did that without a single "ask for permissions" dialog?

Actually the App used in the script should have 'manage_pages' permission. After that the users do not need to grant permissions. Its actually the App that is uploading the image, not the user:)

Hum, i think i dont get it. Where did you give this permissions for your app?

Ok this is how i finally managed it to run:

1. Created an application
2. Logged in as Administrator on Facebook
3. Got an PERMANENT AccessToken by calling graph.facebook.com/oauth/authorize?type=user_agent&client_id=YOUR_APP_ID&redirect_uri=YOUR_REDIRECT_URL&scope=manage_pages, offline_access, user_photos, publish_stream, manage_pages
4. Filled in the PERMANENT AccessToken in the script
5. Logged Out at Facebook
6. Logged in at Facebook as a Testuser (who has no Admin rights for the Fanpage)
7. Sucessfully Uploaded a Photo to the Fanpage Album via Facebook-Application without being prompet for extended "manage_pages" permissions

So no my App (which needs no special permissions) sends the Picture to the php-Script which can upload/manage the Fanpage because of the
Permanent AccessToken which belongs to the Administrator. I don't know if you did it the same way, but luckily this works for me good enough.

So big thanks for sharing your knowledge, i appreciate that!

Where is the 'library/facebook.php' ??

This comment has been removed by the author.

I believe library/facebook.php is the facebook libraries.

https://github.com/facebook/facebook-php-sdk/tree/master/src

P.s. good guide!

Great post. :) I'm a FB newbie after having two years of programming experience with Twitter.

I'm getting:

"Fatal error: Uncaught OAuthException: Invalid OAuth access token signature. thrown in.."

error. I did use the access token in found in the access token tool.. I replaced the username "arvind07" with the admin user name...

Am I doing this right?

@Marcus Belcher, you are right. Facebook library can be downloaded from github or facebook developers site.

@Rob, The steps you followed seems to be correct. However guessing the exact cause of the problem is difficult. Make sure all the IDs and tokens are correct and you are not missing anything.
Good luck:)

My token gets expired, how did you managed that?

Hi Amit,
You need to provide offline_access permission to your application.

How Can I submit the Image directly to the facebook fan page wall instead of the album ??

For publishing images to fan page wall, you can use the graph API. Details are present at https://developers.facebook.com/docs/reference/api/

Can you provide me with the exact syntax to your above code so that i could post the image to the facebook wall?

Currently I do not have the exact code. I may post this article very soon. Keep reading:)

Hello. I am desperately trying to get this work. I am willing to pay $$$ to have someone to get this to work for me. Thanks

Hello. I love this app however I keep getting the oauth invalid token error when I use the (https://developers.facebook.com/tools/access_token/) method. It does work however when I use the (graph.facebook.com/oauth/authorize?type=user_agent&client_id=YOUR_APP_ID&redirect_uri=YOUR_REDIRECT_URL&scope=manage_pages, offline_access, user_photos, publish_stream, manage_pages) method but as soon as I log out the token expires and I have to get a new one. How can I get a permanent token with offline_access and all of the other permissions? Thanks so much. Mike

@socialeyes, which token are you using? There are two types of tokens: user token and app toke. You need to use the 'user token' in your app.

Thanks.

I finally got it_____ Now I am trying to link an online webcam to it but having major difficulty.___ Would you be interested in linking the two and decide on a reasonable $ fee $ that you would charge me. ____ The webcam is at eyesocialeyes.com/webcam/ ___ I want it to work so that when the user clicks upload it sends the image to the page wall. please let me know if you are interested. Thanks

I was able to get this script working, thank you. Any thoughts on how to get the script to also perform actions on the 'guest' behalf? IE. User uploads photo to fan page, but also posts a comment on their own profile? I was getting token errors when attempting. Thank you so much for this article.

your demo page is broken, it seems to be erroring out silently.. can you check on that?

@Gregory Nicholas, Thanks for the notice. Its fixed now.

This comment has been removed by the author.

Thanks... Nice Work Man...
Really Helped Me For My Problem.

hi aravind,

I like your script and am a noob... any pointers on how to code an app for mobile using javascript and HTML 5 that can do this? Any resources might help

which access token do i have to put in your code??

Hi bro, is a great script, I follow all the steps, but I can run the script..., is possible put the code for download? is very important for me use your script :) or if you prefer you can send me via private message to: jvigallego@gmail.com.

Waiting your soon reply.

Cheers.

Hi Arvind is possible provide a download link?, because we try to run the script but only we have errors, and in the live demo run well. Or if you can send me a private mail to: jvigallego@gmail.com thanks in advance! :)

@Montejaque, I have sent you the script.

Hi Arvind plz send me also this script bro..
mca.anish@gmail.com..

Waiting for your reply bro..

@anish, I have sent you the complete script. Please check.

This comment has been removed by the author.

The permanent access token will be deprecated 2 may 2012... how to get a new token via curl or something else automatically?
I just need to use it in my application to post pics in fanpage album.

ideas?

Thank you for sharing! What would I need to change to upload a photo already on my server instead of from my PC? Right now I'm getting error:

Fatal error: Uncaught CurlException: 26: failed creating formpost data thrown in.....

Thanks again!

useful post for those who interest in php and facebook photo upload

Can I please have the complete script of the application...I need it urgently.. Thank you for the help..
arjun231005@gmail.com

@Arjun, I have sent you the complete script. Tha script is available for download for all users :)

This appears to be the way to do this for the admin of a page - in order to get the different typ eof access token, but what about the Fans? (If the page has been set to allow anyone to post?)

I have managed to post a text post to a page (as a Fan) via the API. And also a post with a 'picture' link provided by a url. But not a photo upload.

Any ideas?

Great article, btw.

I tried a few things to get this app to work. I changed everything to my app's settings but it's not working. I got it working for a few hours but it seems the access token expires after a few hours. I now get this error:
I'm getting the following error:
Notice: Undefined variable: fanpage_token in uploadtopage.php on line 96 Fatal error: Uncaught OAuthException: A user access token is required to request this resource. thrown in library/facebook.php on line 543

Does anyone know what to do? Thanks!

how enable offline_access in facebook

hi bro.
my access token a session out so tell me how i get a automatically access token bro?my script is done and its working properly but i have face this problem so help me out bro

Hi,
I've a problem, when I logged as administrator in developer.facebook.com and I get the access token using the tools of developers, the script works well, but the token expire after a some time. I select the offline_access option and click to get the token, but I've the same problem.

Hi,
I've a problem, when I logged as administrator in developer.facebook.com and I get the access token using the tools of developers, the script works well, but the token expire after a some time. I select the offline_access option and click to get the token, but I've the same problem.

Whenever i run this file with your settings it works fine, but when i define my own fan page id and album id, it gives the following errors:

Notice: Undefined variable: fanpage_token in /home/kevinsleegers.nl/public_html/Fundraiser2/index.php on line 96

Fatal error: Uncaught OAuthException: Invalid OAuth access token signature. thrown in /home/kevinsleegers.nl/public_html/Fundraiser2/library/facebook.php on line 543

And it seems like my Acces token only lasts for 1 hour, how can i get one that will last for a longer time / forever?

Please answer, I need to get this to work for a project at school.

I'm having this problem too bro. Can you help us Arvind ?

I'm having this problem too bor. Can you help us Arvind ?

This comment has been removed by the author.
This comment has been removed by the author.

I replaced the variable $access_token to $fanpage_token and it work's. BUT, i just can upload photos in my profile (Personal Page) if i try upload in the album of my fan page [ Uncaught OAuthException: (#120) Invalid album id thrown in ].

Can you help me ? Thank You a Lot

How can we fix the Uncaught OAuthException: (#120) Invalid album id thrown in ??

You have to put this string in the $args array [ access_token' => $fanpage_token ]

You have to put this sting in the $args array:

access_token' => $fanpage_token

Clearly there is a difference between what you have on your demo site and the code you provide, which does not work with users OTHER than the page admin

This comment has been removed by the author.

I was having some trouble earlier using this code.. but if I change the 'voice' of the app, everything worked well after that..
Reference: http://social-chimp.com/blog/change-your-facebook-voice/

hello, i want uploading pic to my page and i dont want to upload it from my computer....i want to upload from server....means stored photos...

Awesome .. !
I was lokking for this ..
tnx a lot buddy .. !!
Cheers ! :)

Hi

Please help me.
I'm getting this issue:

The link doesnt work and I keep getting the following error: "Fatal error: Uncaught OAuthException: (#100) Invalid ID for album owner thrown in /usr/www/users/nikonm/test/imgupload2/library/base_facebook.php on line 1106 "
How do you get the album ID?

Hi,
This is a great post Arvind,
But please, help me with a problem:
The access token from 'https://developers.facebook.com/tools/access_token/' is only a temporary on (they even say not to hard copy it).
Is there a way to get one 'on the fly'?

And, is there a way to let users post a photo to the album?

Thanks a lot!

Hi,
I am using Facebook Graph APIs to upload photo on page's album but I am getting 'Invalid Album ID' Exception.
I have tried with Page Access Token.
Kindly help me out as I have stuck in this problem.

I got it working.
Thanks a lot for this

Is there a way to use this to upload the fan page timeline cover pic? Thanks

This user isn't allowed to upload photos to this object's wall thrown

Pls Help!!

Hi Arvind ,

Please help me . What happens in my case is that I get the access token you gave me
//It can be found at https://developers.facebook.com/tools/access_token/
from the above url but it gets timed out every now and then and then throws error.

How do i get the user access token dynamically?

Please help me . I am stuck.

Hi Arvind,

I need your help. I am stuck at a point pof getting access token . The url you provided //It can be found at https://developers.facebook.com/tools/access_token/ gives me access token but it gets timed out. Please help me how to get the access token of user dynamically in FB. I am new to fb and would really appreciate your help.

Please help me.

Hi, I'd like to be able to use this to upload multiple images at the same time and even better if I can insert it in WordPress includin some captcha.

Can you help me, does it have a cost $?

Hi, I'd ike to be able to use this to upload multiple photos at the same time and even better if I can use this inside WordPress with some captcha.

Can you celp me?
Does it have a cost $?

Please contact me on my email id (bhardwajs.on.height@gmail.com) for any support.

Thanks.

Figured out a way to get a working admin token that doesn't expire.

1. Give your app the manage_pages permission

2. Use the Access Token Tool to get your User Token for your app at (https://developers.facebook.com/tools/access_token/)

3. Once you have this, you can exchange this token for a longer-lived (two months?) token using the following URL:
https://graph.facebook.com/oauth/access_token?
client_id=APP_ID&
client_secret=APP_SECRET&
grant_type=fb_exchange_token&
fb_exchange_token=EXISTING_ACCESS_TOKEN

4. Now, with this access token, we can use the Graph Explorer tool (https://developers.facebook.com/tools/explorer) to find out the NEVER-EXPIRING page access token:
4.1 In the access token field, paste in the long-lived access token that was returned in step 3
4.2 In the query field (making sure it's set to GET) type in the format /accounts where is the username/ID of the admin user with page rights
4.3 Look through your accounts for the matching page, and copy its access token - this is your fanpage access token
4.4 If you test it, in Access Token Debugger (https://developers.facebook.com/tools/debug/access_token/) you will find that it never expires

5. Hardcode this non-expiring token as your $fanpage_token, and get rid of anything in the original code that tries to generate the $fanpage_token including the foreach() loop and the original user access token

-------------------------------------------------------

Hopefully this should work, it's worked so far for me

Ben

@Ben Thanks for this workout. Hope It will help others.

What can you say about recent Facebook update?

https://developers.facebook.com/roadmap/offline-access-removal/

photo upload function works well but Im getting this error when I access uploadtopage.php

Notice: Undefined index: name in /home/buswar/public_html/bonjourlife.com/fan/uploadtopage.php on line 76

success, but why it doesn't show on the timeline, even I post to the Wall Photo album
how to post it to the timeline

i keep getting an error

Notice: Undefined variable: fanpage_token in /mnt/hd1/website/uploadtopage.php on line 96 Fatal error: Uncaught OAuthException: A user access token is required to request this resource. thrown in /mnt/hd1/website/library/facebook.php on line 543

i have this hosted on a ubuntu apache2 server

any ideas?

hi,...

i have appid ,secret id but i dont know how to get album id ,fan page id in facebook so tell me how to get both id ....

hi arvind

i have app id and secret id but dont know how to get album id and fan page id so tell me how to get both id....

I was just checking for this information for a while. After 6 hours of nonstop Googleing, at last I got it in your site. I wonder what’s the lack of Google approach that don’t rank this type of informative sites in top of the list. Normally the top websites are full of trash.

It looks like it works but then the access token expires after an hour or two. How do we run the script without the access token or automatically renew it somehow?

with so many changes it would be greatly appreciated if someone could update this tutorial!

Oh, your banny wrote! Facebook now give temporary access roken with 1 hour expiration and now remove offline_access. How to do? How to get access_token every with first running script?? Help please.

How can I fix the Uncaught OAuthException: (#120) Invalid album id thrown in .. Coz clearly the album exists and has the id I am using for the script. Please Assist

We would love to hear from you...

back to top