How to Auto Post on Facebook with PHP update Graph Api

Share a Link to Facebook using PHP

Here is the code you need to share a link to Facebook using PHP. With small changes you can use this code to post just a message (without link), or to upload a photo in a Facebook album.

Also, with small changes you can use this code to post either to your Facebook Profile or your Fan Pages or Business Pages.

Detailed instructions are provided below in this post.

The following PHP script can be invoked from command line (or Cron) or from your browser.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
<?php
// require Facebook PHP SDK
// see: https://developers.facebook.com/docs/php/gettingstarted/
require_once("/YOUR_PATH_TO/facebook_php_sdk/facebook.php");
 
// initialize Facebook class using your own Facebook App credentials
// see: https://developers.facebook.com/docs/php/gettingstarted/#install
$config =array();
$config['appId'] ='YOUR_APP_ID';
$config['secret'] ='YOUR_APP_SECRET';
$config['fileUpload'] = false;// optional
 
$fb =new Facebook($config);
 
// define your POST parameters (replace with your own values)
$params =array(
  "access_token" =>"YOUR_ACCESS_TOKEN",// see: https://developers.facebook.com/docs/facebook-login/access-tokens/
  "message" =>"Here is a blog post about auto posting on Facebook using PHP #php #facebook",
  "link" =>"http://www.pontikis.net/blog/auto_post_on_facebook_with_php",
  "picture" =>"http://i.imgur.com/lHkOsiH.png",
  "name" =>"How to Auto Post on Facebook with PHP",
  "caption" =>"www.pontikis.net",
  "description" =>"Automatically post on Facebook with PHP using Facebook PHP SDK. How to create a Facebook app. Obtain and extend Facebook access tokens. Cron automation."
);
 
// post to Facebook
// see: https://developers.facebook.com/docs/reference/php/facebook-api/
try {
  $ret =$fb->api('/YOUR_FACEBOOK_ID/feed','POST',$params);
  echo 'Successfully posted to Facebook';
}catch(Exception$e) {
  echo $e->getMessage();
}
?>

From the above code, it is obvious that

  • you have to use Facebook PHP SDK (line 4)
  • you have to create a Facebook app in order to use Facebook API (line 9,10)
  • you have to get an Access Token, so your app can be post on your behalf (line 17)
  • you have to renew Access Token after expiration (about 60 days)
  • you have to get your Facebook id, either for your Personal Profile or for your Fan Pages or Business Pages (line 29)

All these steps are described below. I use a demo app (Demo_auto_post_php) without hiding "sensitive" information like app secret, access tokens etc. The reason is to make the whole process more understandable. Of course, all these "sensitive" data is not valid. This app (Demo_auto_post_php) created just for demo purposes and it has been deleted.

 

Get Facebook PHP SDK

Download Facebook PHP SDK (v.3.2.2 at the time of writing this article) from Github at You may use any library available (in PHP section) of https://github.com/facebook/facebook-php-sdk.

Actually, you need three files (under folder src)

  • facebook.php (the main class)
  • base_facebook.php (other classes)
  • fb_ca_chain_bundle.crt (SSL certificate)

Get and put them in the same directory (for example facebook_php_sdk ).

Facebook PHP SDK (v.3.2.2) Requirements

  • PHP 5.2.0 or higher
  • php CURL extension (install to Debian/Ubuntu etc with apt-get install php5-curl)
  • php OpenSSL extension (already installed in most systems)

How to Create a Facebook app

Step 1 - Go to https://developers.facebook.com/apps and sign in with your account. Then press the button "+Create new app". New app name is Demo_auto_post

 
(click the thumb for full image)

Step 2 - Your new Facebook app is just created

Your Facebook app credentials are now available: App ID and App Secret.

 
(click the thumb for full image)

Step 3 - Disable Sandbox mode and set Canvas URL. Then press "Save changes"

Disable Sandbox mode, so your app will become live (visible to all users).

Click on "App on Facebook" tab and set Canvas URL. I set Canvas URL to "http://localhost/fb-tokens" (andSecure Canvas URL to "https://localhost/fb-tokens"). This is the (local) URL where Facebook will use to redirect some results you need. Of course, you can use any URL you prefer. Please, see below (How to Get Facebook Access Token STEP 1 - create the redirect_uri page) for details.

 
(click the thumb for full image)

Please, note, that, you need a Personal Facebook account in order to create a Facebook app. Then, you can obtain Access Tokens for your Fan or Business Pages. In case you have only a Business Page (without a Personal Facebook profile), you cannot automate post procedure using a Facebook app. In this case you have to create a Personal Profile and then assign you as Admin to Business Page.

How to Get Facebook Access Token

STEP 1 - create the redirect_uri page

First, create a simple php script in your local web server, which has the Canvas URL (redirect_uri) you set creating your Facebook App in STEP 3. I set this URL to http://localhost/fb-tokens/. My local web serverDocumentRoot is /srv/http, so:

1
2
mkdir /srv/http/fb-tokens
nano/srv/http/fb-tokens/index.php

Put the following code.

1
2
3
<?php
print_r($_GET);
?>

This code will just print the php $_GET array, in other words what Facebook will pass to you from query string.

STEP 2 - authorize your app (give permissions)

On your browser, give the following url, where client_id is App ID and redirect_uri is the URL defined as Canvas URL

1
https://www.facebook.com/dialog/oauth?client_id=167252680143474&redirect_uri=http://localhost/fb-tokens/&scope=manage_pages,publish_stream

The part &scope=manage_pages,publish_stream of this URL defines thw permissions you will assign to your app.

Read about Facebook permissions:

  • an introduction here.
  • about Facebook publish_stream permission here.
  • about Facebook manage_pages permission here.

The result will be

authorize your app to access your profile

 
(click the thumb for full image)

click OK

authorize your app to post to your friends on your behalf

 
(click the thumb for full image)

click OK

authorize your app to manage your Pages

 
(click the thumb for full image)

Get the code value

 
(click the thumb for full image)

You will get somenthing like this

1
2
3
4
5
Array
(
[code] =>
AQCnhrD8RSxJRmGJdYCfFD33hGPv84xa-xqXKD1-3i3qmsPjqHODEn1cROQkYv6LSKhKlPBxkPHD9gUs-9W0GSwDJVvarX70QiLAYmcLsGhN2u0Ib1OF512TvMljg8WLjx0FaAFCB1DHiTqYE-6ZNtWqtZpe4aIecOw949QNcWbZOf2BiCH_yECCNfamKdatV5Nv1Oa1IvIi_8_zVGc_cQqujVC_O2Apkzyj7M1cypoucGc02NzpAQv3yPqCnIuz5TWglcvhr2YNL7HAClLW0ydWgmq7FyfXOfrbFLoRjd-GRTevmTCffA2iV_A1i-itStY
)

After getting the code value, give the following url, where client_id is App ID and redirect_uri is the URL defined as Canvas URL, client_secret is App Secret and code is the code got.

1
https://graph.facebook.com/oauth/access_token?client_id=167252680143474&redirect_uri=http://localhost/fb-tokens/&client_secret=29d8d368420dc1e81198fce224ac71c9&code=AQCnhrD8RSxJRmGJdYCfFD33hGPv84xa-xqXKD1-3i3qmsPjqHODEn1cROQkYv6LSKhKlPBxkPHD9gUs-9W0GSwDJVvarX70QiLAYmcLsGhN2u0Ib1OF512TvMljg8WLjx0FaAFCB1DHiTqYE-6ZNtWqtZpe4aIecOw949QNcWbZOf2BiCH_yECCNfamKdatV5Nv1Oa1IvIi_8_zVGc_cQqujVC_O2Apkzyj7M1cypoucGc02NzpAQv3yPqCnIuz5TWglcvhr2YNL7HAClLW0ydWgmq7FyfXOfrbFLoRjd-GRTevmTCffA2iV_A1i-itStY
 
(click the thumb for full image)

You will get the Access Token (!)

1
access_token=CAACYHYyWcnIBAJ1LwRLTERQNXJ4qRCqoTf2pgs1V2AiZCOreWAH0bY2UKaoyD3elfcEZAZAs6fZAEYPAZC5OlU6ZCg8Org32D13LiencxZA0PsNzkQPPuZCiZAukgMnqLXM0F2ZBlYZAnZB08qVwOo6DgiCJSlkoZCb9VVs0ARsleZBcduzTQKZBvIcvjLZBXXr5ye8R4FcZD&expires=5183831

STEP 3 - Access Tokens for your Facebook Pages (if any)

If you have any Facebook Pages (except your Personal Profile), you can get Access Tokens for them, using the following URL, where access_token is the Access Token you just got for your Personal Profile

1
https://graph.facebook.com/me/accounts?access_token=CAACYHYyWcnIBAJ1LwRLTERQNXJ4qRCqoTf2pgs1V2AiZCOreWAH0bY2UKaoyD3elfcEZAZAs6fZAEYPAZC5OlU6ZCg8Org32D13LiencxZA0PsNzkQPPuZCiZAukgMnqLXM0F2ZBlYZAnZB08qVwOo6DgiCJSlkoZCb9VVs0ARsleZBcduzTQKZBvIcvjLZBXXr5ye8R4FcZD

The result will be the following JSON string

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
{
   "data": [
      {
         "category":"Website",
         "name":"pontikis.net",
         "access_token":"CAACYHYyWcnIBAMK1y2tqiRKx8bBXGFFzjdUamOlMZCBJrTSL8ic1z5sZBarBi3DbTh9mMUz3aiZCAQRNHvOmcMxLZC53FNtkrVCq8rZCLsyjbQVZAt8o7S6Rd1UT0LK7AkgyZAlu11MC9rWND8eZBiKjjiYjwmBMLWko7k6GGPZCREehKRNFCsyM1Ll7sFb1hXycZD",
         "perms": [
            "ADMINISTER",
            "EDIT_PROFILE",
            "CREATE_CONTENT",
            "MODERATE_CONTENT",
            "CREATE_ADS",
            "BASIC_ADMIN"
         ],
         "id":"466400200079875"
      }
   ],
   "paging": {
      "next":"https://graph.facebook.com/100005247665389/accounts?access_token=CAACYHYyWcnIBAJ1LwRLTERQNXJ4qRCqoTf2pgs1V2AiZCOreWAH0bY2UKaoyD3elfcEZAZAs6fZAEYPAZC5OlU6ZCg8Org32D13LiencxZA0PsNzkQPPuZCiZAukgMnqLXM0F2ZBlYZAnZB08qVwOo6DgiCJSlkoZCb9VVs0ARsleZBcduzTQKZBvIcvjLZBXXr5ye8R4FcZD&limit=5000&offset=5000&__after_id=491387474252073"
   }
}

Except of getting Access Token for your Fan Pages, the above step is useful to get your Fan Pages Facebook id. You will need it, when you try to post to your Fan Pages. However, this procedure is described independently (see below: How to Find your Facebook id)

STEP 4 - Check your Access Token

Facebook Access Tokens will expire in about an hour. Access Token obtained with the above procedure are long-lived Access Tokens and will expire after two months (60 days).

offline_access permission, used to prevent tokens expiration, was depreceted since 2012. Read more at https://developers.facebook.com/roadmap/offline-access-removal/.

Since offline access is deprecated you cannot create an access token which doesn’t expire. The best you can get is a long-lived Access Token (expires in 60 days).

So, it is very important to know your Access Token expiration time. Just use the URL

https://developers.facebook.com/tools/debug/access_token

For example, to check (debug) the Access Token obtained for this demo

 
(click the thumb for full image)

Notice that this Access Token will expire after 60 days.

I remind you that this app (Demo_auto_post_php) has been deleted, so the above URL will not give you the same results. The above screenshot is taken before app deletion.

Renew Access Token after expiration

Facebook long-lived Access Tokens will expire after about two months (60 days). In order your app to remain functioning, you (unfortunately) have to repeat "How to Get Facebook Access Token - STEP 2".

How to Find your Facebook id

The Facebook id of a Personal Profile of Fan Page or Business Page is public information, available using Facebook Graph API. Just use a URL like:


Tags:



Related Posts


Comments (0)

Leave a Comment

Type the above code here