Upload photos to Facebook Fan Page using PHP

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;
}

Written by Arvind Bhardwaj

Arvind is a certified Magento 2 expert with more than 10 years of industry-wide experience.

Website: http://www.webspeaks.in/

92 thoughts on “Upload photos to Facebook Fan Page using PHP

  1. 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!

  2. 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 🙁

  3. 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?

  4. 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:)

  5. 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!

  6. 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?

  7. @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:)

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

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

  10. 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

  11. 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

  12. 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.

  13. 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

  14. 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.

  15. 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?

  16. 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!

  17. 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.

  18. 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!

  19. 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

  20. 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.

  21. 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.

  22. 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.

  23. 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

  24. 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

  25. 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…

  26. 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?

  27. 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!

  28. 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.

  29. 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 $?

  30. 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 $?

  31. 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

  32. 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

  33. 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

  34. 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?

  35. 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.

  36. 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?

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

  38. 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.

  39. 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

  40. This article Upload photos to Facebook Fan Page using PHP – WebSpeaks is related to web programming is genuinely pleasant in favor of me because I am website programmer. Thanks for sharing keep it up.
    [url=http://joshadamsrealtor.com/canada-gooses/canada-goose-kids_c44]cheap Canada Goose Kids[/url]

  41. What’s up to every , because I am in fact eager of reading this Upload photos to Facebook Fan Page using PHP – WebSpeaks website post to be updated daily. It consists of nice data.
    [url=http://joshadamsrealtor.com/moncler/moncler-womens-down-vest_c201]Moncler Womens Down Vest sale[/url]

Comments are closed.