Saturday, December 17, 2011

Upload photos to Facebook Fan Page using PHP

12/17/2011

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 is a web developer, programmer and blogger. He has expertise in PHP, Magento, WordPress, jQuery, JavaScript, HTML5 and CSS3. He loves to develop good looking websites with strong backend.

90 comments :

  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!

    ReplyDelete
  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 :(

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

    ReplyDelete
  4. 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?

    ReplyDelete
  5. 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:)

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

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

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

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

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

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

    P.s. good guide!

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

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

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

    ReplyDelete
  14. My token gets expired, how did you managed that?

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    ReplyDelete
  29. 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

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

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

    ReplyDelete
  32. 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! :)

    ReplyDelete
  33. @Montejaque, I have sent you the script.

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

    Waiting for your reply bro..

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

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

    ReplyDelete
  37. 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?

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

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

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

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

    ReplyDelete
  42. 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.

    ReplyDelete
  43. 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!

    ReplyDelete
  44. how enable offline_access in facebook

    ReplyDelete
  45. 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

    ReplyDelete
  46. 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.

    ReplyDelete
  47. 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.

    ReplyDelete
  48. 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.

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

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

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

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

      Delete
  49. 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

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

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

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

      access_token' => $fanpage_token

      Delete
  51. 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

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

    ReplyDelete
  53. 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/

    ReplyDelete
  54. 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...

    ReplyDelete
  55. 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?

    ReplyDelete
  56. 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!

    ReplyDelete
  57. 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.

    ReplyDelete
  58. I got it working.
    Thanks a lot for this

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

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

    Pls Help!!

    ReplyDelete
  61. 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.

    ReplyDelete
  62. 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.

    ReplyDelete
  63. 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 $?

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

      Thanks.

      Delete
  64. 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 $?

    ReplyDelete
  65. 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

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

      Delete
    2. What can you say about recent Facebook update?

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

      Delete
  66. 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

    ReplyDelete
  67. 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

    ReplyDelete
  68. 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?

    ReplyDelete
  69. 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 ....

    ReplyDelete
  70. 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....

    ReplyDelete
  71. 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.

    ReplyDelete
  72. 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?

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

    ReplyDelete
  74. 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.

    ReplyDelete
  75. 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

    ReplyDelete

We would love to hear from you...

 

© 2014 Web Speaks . All rights resevered. Designed by Templateism