How to Auto Post on Facebook with PHP

In a previous post I wrote about post automation on Twitter using PHP. The whole procedure is similar. You have to create a Facebook app and you need a PHP SDK to communicate with Facebook API.

However, the Facebook post automation is much more complicated than the relative process for Twitter. This is not a surprise, as Facebook itself is much more complicated than Twitter. For example, except of a Facebook Personal Profile, you may have Fan Pages or Business Pages.

A significant difference is that Twitter Access Tokens will never expire (according to current Twitter policy), while Facebook Access Tokens will expire in 60 days.

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.

<?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

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

Step 2 – Your new Facebook app is just created

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

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” (and Secure 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.

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 server DocumentRoot is /srv/http, so:

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

Put the following code.

<?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

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 OK

authorize your app to post to your friends on your behalf

click OK

authorize your app to manage your Pages

Get the code value

You will get somenthing like this

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.

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

You will get the Access Token (!)

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

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

The result will be the following JSON string

{
   "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

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:

http://graph.facebook.com/username

For example:

To find my Facebook Personal Profile id, use:

http://graph.facebook.com/chr.pontikis

To find Facebook id of my Fan Page (the Fan Page of this blog), use:

http://graph.facebook.com/pontikis.net

You may also use some online tools like http://findfacebookid.com/

DEMO

Here are some demo posts.

Share a Link to Personal Profile

The code is

<?php
require_once("/path/to/facebook_php_sdk/facebook.php"); // set the right path

$config = array();
$config['appId'] = '167252680143474';
$config['secret'] = '29d8d368420dc1e81198fce224ac71c9';
$config['fileUpload'] = false; // optional
$fb = new Facebook($config);

$params = array(
        // this is the main access token (facebook profile)
        "access_token" => "CAACYHYyWcnIBAJ1LwRLTERQNXJ4qRCqoTf2pgs1V2AiZCOreWAH0bY2UKaoyD3elfcEZAZAs6fZAEYPAZC5OlU6ZCg8Org32D13LiencxZA0PsNzkQPPuZCiZAukgMnqLXM0F2ZBlYZAnZB08qVwOo6DgiCJSlkoZCb9VVs0ARsleZBcduzTQKZBvIcvjLZBXXr5ye8R4FcZD",
        "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."
);

try {
        $ret = $fb->api('/me/feed', 'POST', $params);
        echo 'Successfully posted to Facebook Personal Profile';
} catch(Exception $e) {
        echo $e->getMessage();
}
?>

And the result is

Share a Link to Fan Page

The code is

<?php
require_once("/path/to/facebook_php_sdk/facebook.php"); // set the right path

$config = array();
$config['appId'] = '167252680143474';
$config['secret'] = '29d8d368420dc1e81198fce224ac71c9';
$config['fileUpload'] = false; // optional
$fb = new Facebook($config);

$params = array(
        // this is the access token for Fan Page
        "access_token" => "CAACYHYyWcnIBAMK1y2tqiRKx8bBXGFFzjdUamOlMZCBJrTSL8ic1z5sZBarBi3DbTh9mMUz3aiZCAQRNHvOmcMxLZC53FNtkrVCq8rZCLsyjbQVZAt8o7S6Rd1UT0LK7AkgyZAlu11MC9rWND8eZBiKjjiYjwmBMLWko7k6GGPZCREehKRNFCsyM1Ll7sFb1hXycZD",
        "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."
);

try {
        // 466400200079875 is Facebook id of Fan page https://www.facebook.com/pontikis.net
        $ret = $fb->api('/466400200079875/feed', 'POST', $params);
        echo 'Successfully posted to Facebook Fan Page';
} catch(Exception $e) {
        echo $e->getMessage();
}
?>

And the result is

Upload a photo to Facebook Album

The code is

<?php
require_once("/path/to/facebook_php_sdk/facebook.php"); // set the right path

$config = array();
$config['appId'] = '167252680143474';
$config['secret'] = '29d8d368420dc1e81198fce224ac71c9';
$config['fileUpload'] = true;
$fb = new Facebook($config);

$params = array(
        // this is the access token for Fan Page
        "access_token" => "CAACYHYyWcnIBAMK1y2tqiRKx8bBXGFFzjdUamOlMZCBJrTSL8ic1z5sZBarBi3DbTh9mMUz3aiZCAQRNHvOmcMxLZC53FNtkrVCq8rZCLsyjbQVZAt8o7S6Rd1UT0LK7AkgyZAlu11MC9rWND8eZBiKjjiYjwmBMLWko7k6GGPZCREehKRNFCsyM1Ll7sFb1hXycZD",
        "message" => "Here is a blog post about auto posting on Facebook using PHP #php #facebook",
        "source" => "@" . "/home/pontikis/photo.png", // ATTENTION give the PATH not URL
);

try {
        // 466400200079875 is Facebook id of Fan page https://www.facebook.com/pontikis.net
        $ret = $fb->api('/466400200079875/photos', 'POST', $params);
        echo 'Photo successfully uploaded to Facebook Album';
} catch(Exception $e) {
        echo $e->getMessage();
}
?>

The result in the timeline is

and the photo is available in the album

Putting them all together

Of course, you may use these code samples with many ways. For example to post a topic on Facebook just after it is published. Below is how I use this code to post on Facebook every day, using Cron. (I am not referring to this blog. I share pontikis.net posts manually, as the new topics are two or three per week. I use automation for other sites I manage with more than five new topics every day).

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

Remember to put this script in a protected directory of your web server (without public access).

Here is a short description of the script.

  • I use MySQL in this example, but, of course, any database could be used. In my database, the “topics” table has some columns to support post automation to Facebook, as:
    • facebook_post varchar(400) – the text to be posted
    • facebook_image varchar(400) – the URL of the link image (if any)
    • facebook_pubstatus int – “0” means that this topic is pending to be posted, “1” means topic has been posted to facebook
  • First, an array is created ($share_topics), which contains the topics to be posted to Facebook. Obviously, you have to customize the SQL query, according to your database structure.
  • Each array element is posted to Facebook. If no error occured, this topic facebook_pubstatus is set to 1 (so, it will not be posted once more, in case script will run again)
  • The script produces a meaningful report and keeps logs.

    Take care for logfile rotation, for example:

                            nano /etc/logrotate.d/auto_share
                    

    Add the following replace /path/to/… with your path)

                    /path/to/auto_share.log {
                            weekly
                            missingok
                            rotate 4
                            notifempty
                            create
                    }
                    

Here is the code:

<?php
// determine script invocation (CLI or Web Server)
if(php_sapi_name() == 'cli') {
        $line_break = PHP_EOL;
} else {
        $line_break = '<br>';
}

// require Facebook PHP SDK
require_once("/path/to/facebook_php_sdk/facebook.php"); // configure /path/to/... appropriately

// initialize Facebook class using your own Facebook App credentials
$config = array();
$config['appId'] = 'YOUR_APP_ID';  // configure appropriately
$config['secret'] = 'YOUR_APP_SECRET'; // configure appropriately
$config['fileUpload'] = false; // optional

$fb = new Facebook($config);

// get current time - configure appropriately, depending to how you store dates in your database
$now =  date("YmdHis");

// connect to database
$conn = new mysqli("db_server", "db_user", "db_passwd", "db_name"); // configure appropriately

// check connection
if ($conn->connect_error) {
        trigger_error('Database connection failed: '  . $conn->connect_error, E_USER_ERROR);
}

// create array with topics to be posted on Facebook
$sql = 'SELECT id as topic_id, title, url, description, facebook_post, facebook_image, facebook_pubstatus FROM topics ' .
        'WHERE date_published IS NOT NULL AND date_published <= ' . "'" . $now . "' " .
        'AND facebook_pubstatus = 0 ' .
        'ORDER BY date_published ASC';

$rs = $conn->query($sql);
if($rs === false) {
        $user_error = 'Wrong SQL: ' . $sql . '<br>' . 'Error: ' . $conn->errno . ' ' . $conn->error;
        trigger_error($user_error, E_USER_ERROR);
}
$rs->data_seek(0);
while($res = $rs->fetch_assoc()) {
        $a_topic = array(
                "topic_id" => $res["topic_id"],
                "topic_title" => $res["title"],
                "topic_url" => $res["url"],
                "topic_description" => $res["description"],
                "facebook_post" => $res["facebook_post"],
                "facebook_image" => $res["facebook_image"],
                "facebook_pubstatus" => $res["facebook_pubstatus"]
        );
        array_push($share_topics, $a_topic);
}
$rs->free();

// AUTOMATIC POST EACH TOPIC TO FACEBOOK
foreach($share_topics as $share_topic) {

        if($share_topic['facebook_status'] == 0) {

                // define POST parameters
                $params = array(
                        "access_token" => "YOUR_ACCESS_TOKEN", // configure appropriately
                        "message" => $share_topic['facebook_post'],
                        "link" => $share_topic['topic_url'],
                        "name" => $share_topic['topic_title'],
                        "caption" => "YOUR_SITE_URL", // configure appropriately
                        "description" => $share_topic['topic_description']
                );

                if($share_topic['facebook_image']) {
                        $params["picture"] = $share_topic['facebook_image'];
                }

                // check if topic successfully posted to Facebook
                try {
                        $ret = $fb->api('/YOUR_FACEBOOK_ID/feed', 'POST', $params); // configure appropriately

                        // mark topic as posted (ensure that it will be posted only once)
                        $sql = 'UPDATE topics SET facebook_pubstatus = 1 WHERE id = ' . $share_topic['topic_id'];
                        if($conn->query($sql) === false) {
                                trigger_error('Wrong SQL: ' . $sql . ' Error: ' . $conn->error, E_USER_ERROR);
                        }
                        $result .= $share_topic['topic_id'] . ' ' . $share_topic['facebook_post'] . ' successfully posted to Facebook!' . $line_break;

                } catch(Exception $e) {
                        $result .= $share_topic['topic_id'] . ' ' . $share_topic['facebook_post'] . ' FAILED... (' . $e->getMessage() . ')' . $line_break;
                }

                sleep(3);
        }

}

if(php_sapi_name() == 'cli') {
        // keep log
        file_put_contents('/path/to/auto_share.log', $result . str_repeat('=', 80) . PHP_EOL, FILE_APPEND);

        echo $result;

} else {
        $html = '<html><head>';
        $html .= '<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">';
        $html .= '</head>';
        $html .= '<body>';
        $html .= $result;
        $html .= '</body>';
        $html .= '</html>';
        echo $html;
}
?>

Cron automation

Here is an example to run every day on 07:30 (your server time) the auto share php script, using Cron. A mail will be sent with the results.

As root

crontab -e

add the following line

30 7 * * * /usr/bin/php /path/to/auto_share.php | mail -s "Auto share results" you@your-email.com