Thursday, February 23, 2012

Create Album and Upload Photo to Facebook Fan Page using PHP

2/23/2012

In this series of Facebook API tutorials, today we will continue with creating albums on Facebook Fan Page. The main meat of this tutorial is getting the right access token for your fan page. To get the right access token, follow these steps:
  1. Go to https://developers.facebook.com/tools/explorer?method=GET&path=me%2Faccounts 
  2. Enter https://graph.facebook.com/me/accounts in the second text box 
  3. Click on submit 
  4. Json data will be returned 
  5. From that select the access token of your Fan page. 

Other Facebook Tutorials:
How to upload photos to you Facebook Fan Page
Access Facebook Photo Albums using PHP - v1.0
Upload photos on Facebook using PHP
See it working
Live Demo Download Script
<?php
require_once 'library/facebook.php';
$facebook = new Facebook(array(
 'appId'  => '<app_id>',
 'secret' => '<app_sercret>',
 'fileUpload' => true
));
?>
<html>
<head>
<title>WebSpeaks.in | Create album and upload photos to Facebook Fan Page</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head>
<body>
<?php
//It can be found at https://developers.facebook.com/tools/access_token/
$access_token = '<you_access_token>';

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

//The id of the fanpage
$fanpage = '<your_fan_page_id>';

/*
 * Go to https://developers.facebook.com/tools/explorer?method=GET&path=me%2Faccounts
 * Enter https://graph.facebook.com/me/accounts in the second text box
 * Click on submit
 * Json data will be returned
 * From that select the access token of your Fan page
*/
$page_access_token = '<your_page_access_token>';
$facebook->setAccessToken($page_access_token);

$facebook->setFileUploadSupport(true);

//Create an album
$album_details = array(
        'message'=> 'Test album',
        'name'=> 'Album name'.date('Y-m-d H:i:s') //should be unique each time
);
$album = $facebook->api('/'.$fanpage.'/albums', 'post', $album_details);

//The id of the album
$album_id =$album['id'];

//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' => 0,
   '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="Create album and Upload" /></p>
  </form>
 </div>
</body>
</html>

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.

28 comments :

  1. I love you... this is the best article written in much required detail. Please write more - a live saver. One thing - do you have any idea how I dynamically retrieve my administrator's token?

    ReplyDelete
  2. @Nadia thanks.
    For the administrator's token, I believe you can get it from your Facebook user object anyway. Try it.

    ReplyDelete
  3. I received this error
    Fatal error: Call to undefined method Facebook::setAccessToken() in /web/htdocs/www.salernitana.org/home/fbupload2.php on line 32

    ReplyDelete
  4. @minimalista, I think that you are using the wrong access token. Please follow the steps mentioned in the article.

    ReplyDelete
  5. hi in your live demo it says token expired... and i tried your other article too...
    i guess you are making some mistake while feeding in the token.
    actually by researching on net i found out that facebook tokens automatically expire after 1 hour.
    so you need to write code to grab a new access token each time and i tried that for 1 whole day but i was not successful to code that can you help me with that?
    Thank You..

    ReplyDelete
  6. hi in your live demo it says token expired... and i tried your other article too...
    i guess you are making some mistake while feeding in the token.
    actually by researching on net i found out that facebook tokens automatically expire after 1 hour.
    so you need to write code to grab a new access token each time and i tried that for 1 whole day but i was not successful to code that can you help me with that?
    Thank You..

    ReplyDelete
  7. @Dhirendra, Thanks for notice. Demo has been fixed now.

    ReplyDelete
  8. I tested this and it works great.
    Im trying to upload from a form with the javascript FB.api.
    Do you know how to do that?
    I can upload if the image source is a image on my server but not if I get it from the form field.
    Do you have any inputs on what I need to think about when uploading from a form?
    Thanks a lot!.
    Regards Claes

    ReplyDelete
  9. hi,

    I am also facing Dhirendra's problem. the tokens expire. Is there any way to make it more permanent? @Dhirendra have you been able to make the code work?

    ReplyDelete
  10. Hi

    The live demo doesnt display anything. Is this just me? It just displays a blank page.

    I have been struggling with this myself and see the same problem with the live demo.

    Tested in chrome and firefox. Same problem.

    Thanks

    ReplyDelete
  11. @Josh, The live demo has been fixed. Te token needs to be updated after some time intervals.

    ReplyDelete
  12. the live demo get black page, I do tried the code by my self, and the code return album and image id, but I cannot find the albom or the image.

    always get from facebook

    "This content is currently unavailable
    The page you requested cannot be displayed at the moment. It may be temporarily unavailable, the link you clicked on may have expired, or you may not have permission to view this page."

    ReplyDelete
  13. Please. help me.
    Did facebook change the process?
    https://developers.facebook.com/tools/explorer?method=GET&path=me%2Faccounts returns no token on the json.

    ReplyDelete
  14. Please. help me.
    Did facebook change the process?
    https://developers.facebook.com/tools/explorer?method=GET&path=me%2Faccounts returns no token on the json.

    ReplyDelete
  15. Muchas Me a Funciona Perfecto

    ReplyDelete
  16. Hi

    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?

    Thanks

    ReplyDelete
  17. Hi

    Please. help me.
    I am also facing Anonymous's problem.
    Fatal error: Uncaught OAuthException: (#100) Invalid ID for album owner thrown in /home/www/web585/html/facebookshare/php-sdk/src/base_facebook.php on line 1106

    Thanks,

    Alok

    ReplyDelete
  18. 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
  19. hello can someone help me please I'm getting the message

    Fatal error: Uncaught OAuthException: (#100) Invalid ID for album owner thrown in /home/content/63/8650563/html/fmuploader/library/base_facebook.php on line 1106

    ReplyDelete
  20. Demo link Expired Domain!! :(

    ReplyDelete
    Replies
    1. The demo URL works now. Please recheck :)

      Delete
  21. when i try to get a long term user access token i get an error "The access token does not belong to application" after looking in to it i see the access token is asigned to the Graph API app.
    i used https://developers.facebook.com/tools/explorer?method=GET&path=me%2Faccounts
    to get the access token
    did i do something incorrect? i can i make this token last longer then an hour or so

    ReplyDelete
  22. Oh shit! Facebook now remove offline_access token, and temporary user access token generated and expire to 1 hour. How do get access user token for posting fan page wall?

    ReplyDelete
  23. link demo was blroken. Can you fix them. I have tried this code but did'nt work.

    ReplyDelete
  24. Hi many thanks for the code it is working for me. One problem!!! the photos are uploading as an attachment to the fan page. I want the photos to be uploaded as an image directly to the fan page. Is it possible.. please help me.

    ReplyDelete

We would love to hear from you...

 

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