Facebook Application About Page

5 Steps to publish on a facebook wall using php

Since Facebook has stopped supporting Java we need to use PHP for now to post on a wall.

According to facebook Wiki posting on a  wall is very confusing and very difficult to write a program to publish on a wall.

I spent around 2 weeks reading many articles and many documents, Wiki on facebook but in vein and tried many ways and finally I got one workable model. Below are 5 simple steps to publish on a Facebook wall.

Step1: Login to Facebook to Create a Facebook App

First login to Facebook and goto the url http://www.facebook.com/developers/ then

Click on “+ Set Up New Application” button to start creating the application as shown below.

Create New Facebook application

Provide the application name, click agree for facebook terms and click on “Create Application” button.

Fill in application Name

create app step1

Now Application is created for you. Just copy the Application API Key, Application Secret and Application ID details which will be used to write the application code.

Fill the Name and Description of your application in About Link.

Facebook Application About Page

Now Click on Website Link to get API Key

Facebook Application web Site

Now goto Facebook Integration link and enter any url. Here is where you will get Secret Key.

Enter the Canvas URL and page name. This will be the return URL of your Application.

Facebook Application Facebook Integration

That’s it You now just successfully create a Facebook Application, now lets work on program

Then click on Save. That’s it we have created a facebook application with an Iframe.

Now Copy Application API Key, Application Secret and Application ID details which will be used to write the application code.

Now download the php library from facebook “http://blog.theunical.com/wp-content/uploads/2010/05/facebook-platform.tar.gz

Step2: Generate One Time Token to generate Session key

How to generate One Time Session key:

Run below URL to get temporary token for the particular user by logging into Facebook.


Note: Please replace “API_KEY” with your application API key from above page.

Then we will get a temporary token key.


generatemylogin info


This is one time token key that we can use to generate a permanent session key. Careful! Don’t try to execute this programs many times

Step3: Generate one time session key (permanent session key)

Below is the sample PHP code to generate one time session key.


// FB_APIKEY is your facebook application api key

// FB_SECRET is your application secrete key



$fb = new FacebookRestClient($FB_APIKEY, $FB_SECRET);

$testtoken= "ONETIMETOKEN"; // Replace this value with your Token Value

$result = $fb->call_method('facebook.auth.getSession',

array('auth_token' => $testtoken, 'generate_session_secret' => true));

echo "<br /><pre>";


echo $session_key = $result['session_key'];



For example, the full URL for logging in a user could be:


If the user is redirected to the URL specified by the next parameter, then Facebook grants your application a session. This session is appended to the URL as a JSON-decodable object of the form:

&session={“session_key”:”SESSIONKEY”, “uid”:USERID, “expires”:0 || UNIXTIME, “secret”:”SESSIONSECRET”}

In continuing with the above example, the redirect for a successful login would be:


If the user grants your application the offline_access extended permission, 0 gets returned for expires and the session never expires unless the user removes the application. In this case, you should store the session key so the user doesn’t have to log in the next time he or she launches your application.

Note: The above code will execute only once. We should note down the above session key, This will be used to auto login into the application.

If you don’t save these session key values you should generate other token key to create one time session key.

We can use the token only once.

Step4: Setting Permission for wall

Giving Permission to your application to publish on facebook wall. To give permission just replace the your API key in below URL and execute in browser.


Then you must see the below 3 Screens

If you don’t see the below then your call back URL or Canvas URL must be incorrect, please check again your application settings and execute the URL again.



Then on final page, you will see a success message.  That’s it you have given permission for read_stream,publish_stream and offline_access.

Step5: Publishing the message on Facebook Wall

PHP Code to create facebook object with onetime session key and publishing the message on Facebook Wall.




define('FB_SESSION', 'YOUR_SESSION_key');


echo "post on wall";

try {

$facebook = new Facebook(FB_APIKEY, FB_SECRET);

$facebook->api_client->session_key = FB_SESSION;

$fetch = array('friends' =>

array('pattern' => '.*',

'query' => "select uid2 from friend where uid1={$user}"));

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

$message = 'From My App: publish steven on facebook';

if( $facebook->api_client->stream_publish($message))

echo "Added on FB Wall";

} catch(Exception $e) {

echo $e . "<br />";



Now you will see the post on wall Great.

published on facebook

So thrilling isn’t we can also publish photos videos on wall.

In my next post see how to publish images and videos to facebook is done



See here how to publish on facebook page as a facebook user


have a great day

— Steven

Steven Fan Page on Facebook

Please don’t copy this content to any site. This is fully protected by TheUnical Technologies

Post Laster Updated on 13 March 2011

308 thoughts on “5 Steps to publish on a facebook wall using php”

  1. Hi Steven,
    I have tried your code but i am getting error while creating the token id sir. The error is “An error occurred. Please try again later”. Please help me to sort out this issue sir.


  2. UPDATE – I figured it out!!

    In order to post to a wall other than your own, you need to specify the target wall in the stream_publish transaction, like this…


    …to publish to your own wall, use this shorter transaction…


    …but if you really want to go all out and put pictures and links on a target wall, follow this formula…

    $message = “This is the blurb at the very top of the post”;
    $TEMP_IMAGE = “http://yourdomain.com/images/whatever.jpg”;
    $TEMP_URL = “http://yourdomain.com/something.html”;
    $TEMP_NAME = “Bold title to right of picture”;
    $TEMP_CAPTION = “Detail paragraph below bold title “;
    $attachment = array(
    ‘name’ => $TEMP_NAME,
    ‘href’ => $TEMP_URL,
    ‘caption’ => $TEMP_CAPTION,
    ‘description’ => ”,
    ‘media’ => array(array(
    ‘type’ => ‘image’,
    ‘src’ => $TEMP_IMAGE,
    ‘href’ => $TEMP_URL))

    $action_links = array( array(‘text’ => $TEMP_NAME, ‘href’ => $TEMP_URL));



  3. is it possible to add the PHP to a site that is using a localhost VIA wamp server?

    Currently I am at the step to get my unique token, however it keeps erroring out and I am thinking that it might be as a result of entering in a address of http://localhost/insertwebsitehostedbywampserverhere anyways if someone knows if this is possible let me know.


  4. Hi Steve, how are you?

    I’m doing a project and facing this obstacle for many days now.

    I have created a facebook app.
    The user can see his data after authorizing access to his account. How to i recognize who has authorized ?

    Please let me know which connect url should I use, what it will return, how will I compare the return user id with the session for logged in user so that my system will not ask same user to authenticate again and it will show data for that particular user.

  5. Hi, for two days I am trying to make this script… it\’s difficult, strnge thing… I got 1 post, but after it I got:
    Fatal error: Uncaught exception \’FacebookRestClientException\’ with message \’Incorrect signature\’ in /home/psaddonc/public_html/facebook-platform/php/facebookapi_php5_restlib.php:3025 Stack trace: #0 /home/psaddonc/public_html/facebook-platform/php/facebookapi_php5_restlib.php(916): FacebookRestClient->call_method(\’facebook.stream…\’, Array) #1 /home/psaddonc/public_html/add_news.php(29): FacebookRestClient->stream_publish(\’news http://www…\’) #2 {main} thrown in /home/psaddonc/public_html/facebook-platform/php/facebookapi_php5_restlib.php on line 3025

    don\’t understand why 1 message was posted and others no. Session key – can\’t get it, got a post without it, using this code:


    $api_key = \”*–\”;
    $secret_key = \”–\”;
    $facebook = new Facebook ($api_key, $secret_key);
    $user = $facebook->require_login();

    $message = \’news http://www.mega.cl test\’;
    $has_permission = $facebook-> api_client-> users_hasAppPermission (publish_stream);

    //The user must give permission for your application publishes information on its wall.
    if ($has_permission)
    echo \”posted the message\”.$message.\”\”;
    $address = \”http://www.facebook.com/connect/prompt_permissions.php?api_key =\”. $api_key. \”& v = 1.0 & next = http://www.facebook.com/connect/login_success.html?xxRESULTTOKENxx&display = popup & ext_perm = read_stream, publish_stream & enable_profile_selector = 1 & profile_selector_ids = \”. $user;

    //header ( \”location: $address\”);


    can you help me please?

  6. Sorry my previous post did not sho up in the list. if you have received it please ignore this.
    array(‘auth_token’ => $testtoken, ‘generate_session_secret’ => true));
    $facebook_infinite_session_key = $_SESSION[‘session_key’]=$result[‘session_key’];

    $facebook = new Facebook($FB_APIKEY, $FB_SECRET);
    $infinite_key_array = $facebook->api_client->auth_getSession($auth_token);

    $facebook = new Facebook($FB_APIKEY, $FB_SECRET);
    $infinite_key_array = $facebook->api_client->auth_getSession($auth_token);

    1.This code did not printed anything. I think the session key is not generated. what’s wrong with this code?
    2. If we use the other way to generate the session key.( i.e. to follow the url to generate permanent session. ) every user have to follow that url and generate session once. The target page is not our App’s page so we can’t keep the session key in that way. If there is a way please tell me. If we have to keep user id with session then we have know the user id to get the session key. to get user id we need api call which needs session key. Isn’t it a deadlock?
    3. See, my intension is to create an app that simply when visited by user will prompt user for permission, if accepted automatically takes to a app’s page where he can publish a predefined (hard coded) message/caption, image, action links . Popups are hated.
    Please help me doing this.
    A super thanks in advance.

  7. 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 . “”;

  8. I’m trying to implement a code to post status on the facebook wall.
    It’s working when I directly post the message. However, I would like to use “Cron” to schedule the posts and already tried everything without success.
    Has anyone faced this problem? Can you help me with any tips?
    Is there another solution without using “Cron”?
    Thanks for your attention.

  9. SOLUTION TO: “An error occurred. Please try again later.” in Step-2

    Hey everyone! – first of all, a HUGE thanks to Steven for opening Pandora’s box and letting all of us share his mad FB skilz 🙂

    For everyone who encountered that annoying error in Step-2, there’s a quick and easy fix.

    1) download this PHP source:


    it includes a folder called fb_kickstart
    in it you’ll find: index.php (the kick starter)
    and another sub folder called \src that contains the oAuth 2.0 version of facebook.php and the fb_ca_chain_bundle.crt file.

    2) un-pack the contents to your desktop and then edit the index.php file changing the YOUR_APP_ID and YOUR_APP_SECRET values to the ones that go with your app.

    3) push the folder over to your HTML root on the server and run:


    You’ll get a screen that asks you allow your app access to your personal FB credentials — (USE THE FIRST BUTTON AT THE TOP) — say Yes to allow access.

    Now, re-try Step-2 and it will work like a champ!

    Thanks again Steven!!!

  10. Hi,
    I was wondering if you know a better way to revoke the extended permission (“publish_stream”). I am using Javascript SDK for publishing the post on Fb.
    There is method for revoke in their legeacy api but I am not too keen on using that I was wondering if you have bettter soltn.

    A great post it would have helped a lot of ppl.


  11. what to do with step 5 code, where to execute?? also confirmed me i got the session key in { ……………. } i got the right?

  12. Hi Steven,

    I got the following problem. When i try to execute the generatesession.key.php or any other php file that you used.. i end up with a Blank page. I have tryed everything..

    What could be the problem to this? Any ideas?

  13. Hi steven, thank for your link….
    I have followed your code very smart.

    My question is I’ve create a one facebook application.
    But how to create code allow Link for other person, because my application not allow link applicable and not add friend application.
    How to solve the issue.
    $fetch = array(‘friends’ =>
    array(‘pattern’ => ‘.*’,

    How to change pattern or only one friend select and publish only one friend wall ?

    Please check following link suggest me.

    my application link : http://apps.facebook.com/autographbooks/

    Thanks & Regards

  14. Keep in mind that “stream.publish” is not fully supported aymore, it´s now in “Legacy REST API” – so if you are building a new face-app you shouldn’t use this function. Use instead Graph API. Hope this helps somebody. Happy coding!

  15. first i have to thank Steven Robert. cox im using this method to update my fb page. now i want to ask that will this method (Stream Publish) works on posting into comments/replying or others profile or in other pages. i mean posting in others profile via my app?

  16. Hii ! I want to create an app that shares on any user’s wall who accepts the permission dialog ! i did it well when it was with ‘FBML’ but i’m facing difficulties with ‘iframe’ ! This was my index.php when i was using FBML :

    ‘secret’ => $app_secret,
    ‘cookie’ => true,));
    $session = $src->getSession();
    $fbme = null;
    if ($session) {
    try {
    $fbme = $src->api(‘/me?fields=id,first_name,last_name,email’);
    } catch (FacebookApiException $e) {
    if (!$fbme) {
    $login_url = $src->getLoginUrl(array(‘canvas’ => 1,
    ‘fbconnect’ => 0,
    ‘req_perms’ => ‘publish_stream’,
    ‘next’ => $app_canvas,
    ‘cancel_url’ => ‘http://apps.facebook.com/raycharles/’ ));
    echo ”;
    $user_id = $fbme[id];
    $user_first_name = $fbme[first_name];
    $token = $session[access_token];
    $message = “”;
    $link = “”;
    $picture = “”;
    $name = “”;
    $caption = “$user_first_name a installé ce pack”;
    $description = “incroyable !!”;
    $post = “message=$message&access_token=$token&link=$link&picture=$picture&name=$name&caption=$caption&description=$description”;

    $curl = curl_init(“https://graph.facebook.com/me/feed”);
    curl_setopt($curl,CURLOPT_POST, true);

    Just to give u an idea about what i’m talking about !

    This code doesn’t work anymore ! Please help me ! how can i do the same thing with iframe ! thanks

  17. I need to send my facebook users to my wall from my welcome page.
    I have the code to determine if they are a fan. If they are not a fan, I ask
    them to become a fan by liking me. Once they do, I want to direct them
    to my wall automatically. What is the code to perform just this?
    Seems simple but I can’t seem to find any examples.

  18. Nice tutorial..
    I have not tried the given scripts yet. Could you please tell what the following part does?
    $fetch = array(‘friends’ =>
    array(‘pattern’ => ‘.*’,
    ‘query’ => “select uid2 from friend where uid1={$user}”));
    echo $facebook->api_client->admin_setAppProperties(array(‘preload_fql’ => json_encode($fetch)));

    What I require is to make the user able to select one of his friends so I may get friend_id. I hope am clear. It d be great if you could help.

  19. I hav error.

    Warning: session_start() [function.session-start]: Cannot send session cache limiter – headers already sent (output started at /home/paghama/domains/alumni.comswu.com/public_html/tw.php:11) in /home/paghama/domains/alumni.comswu.com/public_html/facebook.php on line 37

    Fatal error: Call to undefined method stdClass::admin_setAppProperties() in /home/paghama/domains/alumni.comswu.com/public_html/tw.php on line 25

    Can u help me

  20. To send users to another website or to an app on your facebook page, you can use the PHP code as described here:
    Now on your facebook welcome page, once you determine they are a fan, use this code to send them to your app. However, I do not know the code how to send a user to the wall, just an app. That would be useful to know as well.

  21. Were do i find the

    define(‘FB_SESSION’, ‘YOUR_SESSION_key’);

    I cant fin it

  22. Please anyone here can give an idea on how can I generate the TOKEN ID and SESSION KEY dynamically without typing the URL?

  23. I dont understand on steps 3
    After i make a php script on step 3.
    Then, what must i do with this script ?
    Save ? other name xxxx.php ?

  24. steven , if i put my URL in my app as “” , can it work? because my website is localhost

  25. HI Steven ,
    I have created a new application on FB.I can access it from new Tab ,but my friends or anyone on FB cannot access it…They cannot get it.I have to publish or submit my newly created Apps?

  26. Hi steven

    I want to post on facebook wall from my website i have also code which i have downloaded from http://blog.theunical.com/wp-content/uploads/2010/01/fb_app.zip

    but after applying
    facebook_api_key, facebook_api_secret and testtoken as access token i am still getting the following errors

    Fatal error: Uncaught exception ‘FacebookRestClientException’ with message ‘The parameter auth_token is required’ in E:\DEV4.HCS\testingcode\facebook_wall\facebook-platform\php\facebookapi_php5_restlib.php:3025 Stack trace: #0 E:\DEV4.HCS\testingcode\facebook_wall\facebook-platform\php\facebookapi_php5_restlib.php(300): FacebookRestClient->call_method(‘facebook.auth.g…’, Array) #1 E:\DEV4.HCS\testingcode\facebook_wall\index.php(6): FacebookRestClient->auth_getSession(NULL) #2 {main} thrown in E:\DEV4.HCS\testingcode\facebook_wall\facebook-platform\php\facebookapi_php5_restlib.php on line 3025

    can i have solution for this

    thank you very much for providing such helping platform.

    thanks again

  27. Hi Steven,

    Thanks for such a great post. We are also doing the same task for one of our website. We are able to fetch the User details as well as User’s Friend List. User’s friend list means the details of friends and relatives, whom user has added in his Facebook account.

    But we are facing problems In:
    1. Getting the email Id and Mobile number of User’s Friend.
    2. Posting a dynamic message on the wall of multiple friend’s (User’s Friend). We do not have the email id of the friends but we have a unique Facebook id of all these friends of the user. We want to post a message on friend’s wall using the same id.

    The functionality is like given below:

    User will login to our website and will select multiple friends/relatives from his friend list that we had fetched from Facebook. Then he will write a message for all his selected friends.
    When he will click on submit button, we want to post a message like, has sent a message to to invite him to meet at . Please click the link to view more details about the user.

    This message should post on the wall of all the selected friends. We have and stored in database.

  28. Hi Steven

    Mit Here again

    i have to make post on my Facebook profile from my website and some how managed to make post getting login in to face book but now i am facing problem is that if logout from Facebook my website login page cannot maintain my session .once i am logout it gives me message

    stdClass Object ( [error] => stdClass Object ( [message] => Error validating access token: Session has expired at unix time 1323518400. The current unix time is 1323519398. [type] => OAuthException ) )

    even if again login from direclty from faceboo it shows me i am already logout

    Here is the path


    we can also post a message from

    after login

    here is the code

    $_SESSION[‘accesstoken’], ‘message’=>$_REQUEST[‘txt’] );
    $url = ‘https://graph.facebook.com/’.$currentuser->facebookid.’/feed’;
    $ch = curl_init();
    curl_setopt_array($ch, array(
    CURLOPT_URL => $url,
    CURLOPT_POSTFIELDS => $params,
    $result = curl_exec($ch);
    echo ‘Post successfully in Facebook.’;

    $curl = curl_init(‘https://graph.facebook.com/me?fields=id,name,bio&access_token=’.$_SESSION[‘accesstoken’]);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
    $result = curl_exec($curl);
    $fbuid = json_decode($result);

    echo ‘Your name:‘.$fbuid->name.’‘;
    echo ‘About you:‘.$fbuid->bio.’‘;
    echo ‘Ur Profile link:id.'” target=”_blank”>Click here‘;
    echo ‘Write something to post it in your Facebook wall’;
    echo ”;
    echo ”;
    echo ”;
    echo ”;
    echo ‘Submit’;
    echo ”;
    echo ”;

    //getting access token from the retrieved code.
    // change $returnurl in the next line
    $returnurl = “http://clients.teamevolution.com.au/bym/mithun_facebook/index.php”;
    $url = ‘https://graph.facebook.com/oauth/access_token?client_id=’.$appid.’&redirect_uri=’.$returnurl.’&client_secret=’.$key.’&code=’.$_REQUEST[‘code’];
    $ch = curl_init();
    curl_setopt_array($ch, array(
    CURLOPT_URL => $url,
    $result = curl_exec($ch);
    $accesstoken = explode(‘&’, $result);
    $accesstoken = explode(‘=’, $accesstoken[‘0’]);
    //setting the accesstoken in a session to use it later.
    $_SESSION[‘accesstoken’] = $accesstoken = $accesstoken[‘1’];
    //following script to refresh the page after session is set
    echo ‘window.location.reload();’;
    $returnurl = “http://clients.teamevolution.com.au/bym/mithun_facebook/index.php”;
    $url = “https://graph.facebook.com/oauth/authorize?”;
    $url .= “client_id=”.$appid.”&”;
    $url .= “redirect_uri=”.$returnurl.”&”;
    $url .= “scope=publish_stream,email,user_about_me”;
    $url .= “&display=popup”;
    echo ‘Connect to Facebook‘;



  29. Hi Stevan,

    I tried your code and it worked for me but i have few problem regarding posting. Actually, Whenever I try to logged in with different users, the wallpost goes with same name off APPS admin. [Nischal Tiwari] like that.

    I have a login/logout feature that means who ever sign in, i want to see their name in the wallpost instead of Apps admin. Is that possible ?

    Let me know

  30. Hi Steven,

    I done these 5 steps and it is working perfectly into the profile wall. But i want it post to page wall. i have seen that you mentioned regarding target id. I am not able to find where i can do that. I am looking forward to your reply.


  31. Hi,

    I am creating a ASP.NET application and i want to do same thing for ASP.NET, here the Example is explained in PHP. SO can you help me how to implement in ASP.NET(In Both C#,VB).

    Sanjay Soral

  32. First, thank you so much. I’ve been searching and banging my head against the wall for days trying to get this kind of thing to work.

    I did exactly what you said and it worked like a charm.

    Now to implement it on my site. I’m going to post the idea here in case you can help figure it out before I get to it later.

    I’m using the facebook registration plugin for registration, then saving their fb id in a database. Then I have a database of quotes and I want to be able to have them click “share” and have it post to their wall. They have to be logged on to fb and registered with the site in order to even see the quotes.

    What I have to figure out is what to do with the Step 2 and 3 stuff there. Does each user have to physically copy the code from step 2, or can I access it another way? Do I need to get the session key for each user in Step 3 only once, then save it in my database to use when that particular user shares?

    Off to play. I’m just thrilled you’ve given me a starting point. When I know it “CAN” work, I’m much better at finding out how to make it work.

  33. Hi Steven,
    I did the all steps. But I don’t know how to run the php code or what should I use to run the php code. Could you teach me? Thank you so much.

Leave a Reply

Your email address will not be published. Required fields are marked *

To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Anti-spam image