Auto Post on Facebook Using PHP SDK v5



This tutorial is about, how you can auto post on Facebook using PHP SDK v5. To auto post on Facebook you need a Facebook app with App ID and App secret. Also you need an Access Token of the user and Facebook PHP SDk v5.

Create Facebook APP:
To create a Facebook App please follow the steps of my previous post How to Auto Post on Facebook Using PHP and get the App ID and App secret key.

Get Facebook Access Token:
Now to get Facebook Access Token you need to use a PHP SDK (v5.0) to communicate with Facebook API. You can download PHP SDK 5.0 from following link Download Facebook PHP SDK v5.0.

Now follow my previous tutorial about Get Facebook Access Token Using PHP SDK v5 to get Access Token. You can store this Access Token to use it in future.

Auto Post on Facebook:
Now create a file autopost.php and write following code in it.

require_once __DIR__ . '/FacebookSDK/src/Facebook/autoload.php';

$fbData = array(
	'consumer_key' => APP_ID,
	'consumer_secret' => APP_SECRET,
	'default_graph_version' => 'v2.2'
);

$fb = new Facebook\Facebook($fbData);

//// get following data from the db or just replace them ////
$params["message"] = '{title}';
$params["link"] = '{targetUrl}';
$params["picture"] = '{imgUrl}';
$params["description"] = '{description}';

// get access token from the database or you can directly put here
$access_token = '{AccessToken}';

// post to Facebook
try {
  // Returns a `Facebook\FacebookResponse` object
  $response = $fb->post('/me/feed', $params, $access_token);
} catch(Facebook\Exceptions\FacebookResponseException $e) {
  echo 'Graph returned an error: ' . $e->getMessage();
  exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
  echo 'Facebook SDK returned an error: ' . $e->getMessage();
  exit;
}

$graphNode = $response->getGraphNode();

echo 'Posted with id: ' . $graphNode['id'];

When I posted a post with following data

$title = "Auto Post on Facebook Using PHP SDK v5";
$targetUrl = "http://www.tricksofit.com/2015/08/auto-post-on-facebook-using-php-sdk-v5";
$imgUrl = "http://www.tricksofit.com/wp-content/uploads/2015/08/Auto-Post-on-Facebook-Using-PHP-SDK-v5.png";
$description= "This tutorial will help you to auto post on Facebook using PHP. For this you need FB app with App ID, App secret, PHP SDK 5.0 and access token of the user.";

I got following as a result.

an auto post example
An auto post example

This way you can auto post on Facebook timeline of the user. You can use this script with cron also. Hope this tutorial will help you.