How to upload a photo to facebook using php sdk 3.2

| | 2 min read

I had a requirement in one of my Drupal projects to post a picture on Facebook automatically. We have many modules in Drupal to be used for the same task but the most simplest way is to use PHP sdk. To auto post a picture on Facebook we need

  • PHP SDK - to communicate with Facebook API
  • Facebook app

Here i am using PHP SDK version 3.2 for uploading process. For downloading PHP SDK go to the link https://developers.facebook.com/docs/php/gettingstarted/3.2.3 and click the download button.

The next step is create an Facebook App. To create an Facebook app go to the link https://developers.facebook.com/. we can login to this account using our Facebook account credentials if we are registered developer account using this credentials.

  • Go to the path My App >> Add a new app >> Website >> skip and create App id.
  • After filling the popup form click create app id button. We get an App id and secret key of an App.
  • Then we have to find access token of Facebook App. For this go to the path Tools and support >> Graph API Explorer and click get access token button. Never forget to check the needed user data permissions and extended permissions especially path publish_actions.

Please find the code to auto post images to Facebook. Please ensure to include facebook.php file from PHP sdk



require 'src/facebook.php';

$file = "pic.png";

$post_type = '/me/photos';

$post_params = array(

'access_token' => "Acess token of facebook App",

'title' => 'title of the image',

'source' => '@' . $fil ,

);

$facebook = new Facebook(array(

'appId' => 'Facebook app id',

'secret' => 'Facebook secret key'

));

$facebook->setFileUploadSupport(true); 

try{

$fbpost = $facebook->api($post_type, 'POST', $post_params);

} catch (Exception $e) {

echo $e->getMessage();

}


The response of the code is id of the uploaded image.