Automatically post to Facebook from PHP script

[Updated 21-09-2012 to support the latest Facebook changes] The importance of a professional presence on Facebook is constaltly increasing.

However supporting and publishing content on Facebook as a parallel channel to a normal website means increased work for many companies.

However posting on facebook doesn’t have to be a manual task that requires extra work. This post guides you to a solution that can easily be integrated in a existing CMS system, and enable cross posting of content to Facebook.

Facebook constantly changes their SDK and methods for communicating with Facebook. The script in this post supports the latest Facebook authentication changes that will be implemented i October 2012.

This post guides you through the creation of a PHP based Facebook application that can automatically post messages and other types of content on your Facebook wall.

The final result of the script is a timeline post like the example below

The post features both a headline, a link to a website, a image, and action links.

The process of building the post to Facebook PHP script requires the following steps:

  1. Download Facebook PHP SDK
  2. Register the Facebook application
  3. Build the Post to Facebook script

Download the Facebook SDK

First step is to create a folder on your webserver for the Facebook application. In this example we’ll name the folder “facebook”

In the facebook folder create a subfolder names “facebook_sdk”

Download the Facebook PHP SDK from GitHub, unzip the files and upload the files to the “facebook_sdk” folder on your server.

The Facebook SDK files can be downloaded from here

Register the Facebook application

Facebook only allows registrated applications to interact with Facebook accounts and pages. The next step is therefore to register your application (even if it hasn’t been built yet) .

You can register a new Facebook application on this page

To register your Facebook application you need first need to provide a unique app name.

If everything is OK, you get to a registration conformation screen, where you get the two important informations:

  • App ID/API Key
  • App Secret

These informations are required for the application to be allowed to communicate with Facebook, but should also be kept as a secret.

Build the Post to Facebook script

Now it’s time to build the actual PHP script for posting to the Facebook timeline.

The script assumes that you have downloaded and unzipped the Facebook PHP SDK (with it’s original file structure and content) in a subfolder named “facebook_sdk”.

The script is divided into three parts:

  1. Configuration where you insert your Facebook SDK information, and configeres which content to post on Facebook
  2. Facebook authentication and posting if a valid access token is avalilable
  3. Facebook authentication token download if no valid token is available (and then the script proceeds to step 2)
 require_once 'facebook_sdk/src/facebook.php';

// configuration
 $appid = '<insert app id>';
 $appsecret = '<insert app secret';
 $pageId = 'myoutlets';
 $msg = 'Nice script for posting to Facebook from PHP program';
 $title = '';
 $uri = '';
 $desc = 'Learn how to build a script that automatically can post messages from a PHP script to Facebook';
 $pic = '';
 $action_name = 'Go to Tips4php';
 $action_link = '';

$facebook = new Facebook(array(
 'appId' => $appid,
 'secret' => $appsecret,
 'cookie' => false,

$user = $facebook->getUser();

// Contact Facebook and get token
 if ($user) {
 // you're logged in, and we'll get user acces token for posting on the wall
 try {
 $page_info = $facebook->api("/$pageId?fields=access_token");
 if (!empty($page_info['access_token'])) {
 $attachment = array(
 'access_token' => $page_info['access_token'],
 'message' => $msg,
 'name' => $title,
 'link' => $uri,
 'description' => $desc,
 'actions' => json_encode(array('name' => $action_name,'link' => $action_link))

$status = $facebook->api("/$pageId/feed", "post", $attachment);
 } else {
 $status = 'No access token recieved';
 } catch (FacebookApiException $e) {
 $user = null;
 } else {
 // you're not logged in, the application will try to log in to get a access token
 header("Location:{$facebook->getLoginUrl(array('scope' => 'photo_upload,user_status,publish_stream,user_photos,manage_pages'))}");

echo $status;

Next steps

This post guided you through the initial Facebook application registration, and basic script for automatically posting content to a Facebook wall.

Next step could be to integrate this script in your CMS system, so a new post is automatically added to Facebook every time you’re updating the content on your site.

Facebook application authentication is changing from october 2012, which means that it’s no longer possible to generate permanent or offline access tokens. Unfortunately this means that it’s getting more complicated to post to Facebook from a application – especially if the Facebook application is running through a cron job or similar.

Share and Enjoy

  • Facebook
  • Twitter
  • Delicious
  • LinkedIn
  • StumbleUpon
  • Add to favorites
  • Email
  • RSS
fold-left fold-right
About the author
Jørgen Nicolaisen has been passionately interested in everything online since 1995. His experience is based on working with small hobby projects as well as high volume websites. Jørgen is currently focused on the PHP based programming framework - Codeigniter, and WordPress naturally

22 Replies to Automatically post to Facebook from PHP script

  1. Rey says:

    Perfect, I just did this tutorial, and all was perfect, Thanksss !!!

  2. Rey says:

    Hello, I got a problem now, from my PC this script works fine, but when I try to post from other PC it redirects me to facebook login page, why is that ??, I just set the app id and secreet correctly, but this script the “fb_access.php” it should automatically log me in right ?? but it is not happen


  3. Rey says:

    is there a way to log in to FB using the API but whit out write the email and pass in a form ??

  4. Cristi says:

    Thanks for sharing, I’ve followed the instruction and finaly made a script that can post on facebook (non blog).

  5. Hi, tx for this great tutorial, but i have the following problem: when my users register their posts on my sie are automtically posted on their facebook wall, but after a short period (1h) the posts aren’t being posted on their walls… it seems that the procedure as you describes in you tut only works for a limited amount of time… any ideas?

  6. Quentin says:

    Appreciate the tutorial. Can this be used as part of a form post? Could I submit form values to the feed?


  7. knisty says:

    thank you
    its a very good script
    but its working only when the array is static

    array(‘message’ => ‘this is a test…’)….

    but when its like this

    $a = $_POST[‘b’];
    array(‘message’ => ‘$a’)….

    its not working
    any idea??????

  8. Filipi says:

    Good morning Steve, sorry to my english.

    I can post status in the wall, but when use cron not work… Already try everything and cannot to use cron for automatize. Can be anything permission? if not use cron work!

    My code:

    api_client->session_key = FB_SESSION;

    $fetch = array(‘friends’ =>
    array(‘pattern’ => ‘.*’,
    ‘query’ => “select uid2 from friend where uid1={xxx}”));

    echo $facebook->api_client->admin_setAppProperties(array(‘preload_fql’ => json_encode($fetch)));

    $sql = $base ->query(‘SELECT * FROM wall WHERE DATE_FORMAT( data_agendada, “%H:%i” ) = DATE_FORMAT(“‘ . date(‘Y-m-d H:i:s’) . ‘”, “%H:%i”) ‘);

    while ($result = $base ->tupla($sql)) {

    echo $result [‘text_facebook’].””;

    echo “sign in”;

    if ($facebook->api_client->stream_publish($resultado[‘text_faceboon].” Testing cron”))
    echo “Added on test FB Wall”;
    } catch (Exception $e) {

    echo $e . “”;

  9. brunda says:

    Iam not getting prop[er output
    when i execute the script it is showing
    api(‘/me/feed’, ‘POST’, array(‘message’ => ‘this is a test…’)); var_dump($status); ?>

    my facebook url is

    pls help

  10. Stan Razvan says:

    hello jhnidk, i have a problem i use the php sdk v3.0.1 and when i try to acces the fb_access.php file so i can grant access to my wall the page goes only blank. I’ve searched the web but i haven’t found any solutions. Any sugestions would be appreciated.

  11. All i get is a blank page when i go to fb_access.php
    and my status script

    Nothing happens.

  12. Stalin says:

    Hi thanks in advance, I got the following error why?

    Fatal error: Uncaught OAuthException: Invalid OAuth access token signature. thrown in /home/thagatpa/public_html/stalin/fb/base_facebook.php on line 1042

  13. ozo says:

    hi, i am having the same issue. when i run the fb_access.php file, i get a blank!!!

  14. Felix says:

    Same Problem. Any idea why I see only a blank page when going to fb_access.php?

  15. Jazirah says:

    I am interested for automatic posting on facebook. thank the tutorial.

  16. I’ve read tutorial at, and this topic. When this script running it posted a message to User’s wall. I’ve replaced /me/ to specific page_id but it does not running.

    $ret_obj = $facebook->api(‘/my_page_id_here/feed’, ‘POST’,
    ‘link’ => ‘’,
    ‘message’ => ‘Some text here’

    Please tell me why it does not running?

  17. Jagan says:

    The script is not working,

    Fatal error: Uncaught OAuthException: (#200) The user hasn’t authorized the application to perform this action thrown in /home/pavointl/public_html/ on line 1039

  18. CACA-COBRA says:

    I just get a blank page when acess fb_access.php

  19. Fred says:

    I have followed your steps, up to the section where I am meant to run the page “fb_access.php” (load the page through my browser). But I keep getting an error message saying “Parse error: syntax error, unexpected ‘(‘, expecting ‘}’ in /fb/fb_access.php on line 14


  20. Hi!

    I followed all the steps with double check but at the end i got a blank page when run the fb_access.php file.

    Looking for solution?


  21. Bryan R says:

    I’m also getting a blank screen when I run fb_access.php. Did anyone find a reason/solution to this issue? Thanks.

Trackbacks for this post

  1. Posta som sidaistället för anvädare på facebook |

Comments are now closed for this article.