Automatically post to Facebook from PHP script

Post to Facebook automatically from PHP scriptFacebook is currently on of the most important publishing and traffic generating sources for many websites. Manually Cross publishing content on your own site and Facebook seems like a lot of extra work.

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

Getting started

Building a php script that automatically posts status updates on your wall requires the following steps:

  1. Download Facebook API
  2. Register a Facebook app
  3. Give the app rights to post on your wall
  4. Build the post to Facebook script

Get the Facebook API

First step is to download a general Facebook communication class from Glithub.

Download the files and upload the files to your site – e.g. to a folder called fb.

The file containing the Facebook class is “facebook.php”

Register a facebook app

Facebook only allows registrated apps to interact with Facebook accounts and pages. The next step is therefore to register your app.

You can register a new app on this page

To register a Facebook App you need to provide: Site name, Site url (with ending “/”) and the locality of your application.

Facebook appliction creation

If everything is OK, you get to a registration conformation screen, where you get the two important informations: App ID and App Secret that you need in the next steps.

Application registration confirmation facebook

Give the application the rights to access your wall

Next step is to build a small script that only has one purpose, identify itself with the new App ID and App Secret to your Facebook account, so you can allow it to directly communicate with your Facebook page.

If you skip this step, you need to manually allow the script to access your Facebook account each time it’s trying to post something, which isn’t that smart…

Simply insert your App ID and App Secret in this script below and  save the script as “fb_access.php” or something similar.


<?
require_once 'facebook.php';

$app_id = "<insert App ID";
$app_secret = "<insert App Secret>";

$facebook = new Facebook(array(
 'appId' => $app_id,
 'secret' => $app_secret,
 'cookie' => true
));

if(is_null($facebook->getUser()))
{
 header("Location:{$facebook->getLoginUrl(array('req_perms' => 'user_status,publish_stream,user_photos'))}");
 exit;
}
?>

Next step is to upload the script to the same directory on your server where you uploaded the “facebook.php” class. In this example we’ll call the script “fb_access.php”

Finally you need to upload the script to your server, and access the script from your web browser: http://<yoursite>/fb/fb_access.php.

Give facebook application access to account

Click the allow button, and you’re ready to build a script that posts to Facebook.

Depending on your Facebook configuration you might get an error message when accessing fb_access.php in your browser.

Facebook error

This typically means that you need to provide a url to the website connected in the application. Simply click the link “application settings editor” and provide: Site URL in the “Web site” tab, and try to load the fb_access.php file again in your browser.

Build the Post to Facebook script

Now that your application has access to your Facebook account, and we have the general facebook.php class, it’s very easy to build a small script that can post messages to your Facebook wall.


<?
require_once 'fb_access.php';

// add a status message
$status = $facebook->api('/me/feed', 'POST', array('message' => 'this is a test...'));
var_dump($status);
?>

And that’s it. Try to access the script from your browser and check if a post is added to your Facebook wall.

Please notice that if you controls multiple Facebook pages, this script will post to the wall of your personal profile. If you want to post to a specific page, you need to replace “/me/” with the ID of the specific page.

Another important information is, that  you will get an error message if you try to post the same message twice. So remember to change the message, when you’re testing the script.

Next steps

This post guides 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.

This script is very basic and only adds a status message in plain text. However you can naturally also post images, links, and other informations. You can see more about the additional informations you can include here.

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 with a multimillion $ annual revenue. Jørgen is currently focused on the PHP based programming framework - Codeigniter, and WordPress naturally

21 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

    thankss

  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?

    Thanks!

  7. knisty says:

    hello
    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 http://www.facebook.com/pages/Blood2all/186945688016420

    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 page..help!!!

  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 http://developers.facebook.com/docs/reference/php/facebook-api/, 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’,
    array(
    ‘link’ => ‘http://www.saokim.com.vn/’,
    ‘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/theprogrammersguide.com/facebook/src/base_facebook.php 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
    “.

    Thanks

  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?

    Regards,
    mshuja

  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.

Leave a Reply