Using facebook off-line access to post on user's wall

Notice: This article is updated (july 2011) after initial publish because of changes in facebook API.

This is simplified and robust example how you can post on user's wall when she/he is not currently logged in or not using your application. It's achieved by by using stored access_token. Access tokens are needed to make calls on facebook graph api. Before that user has to allow offline_access permissions to your app. But let's take it step by step.

Also you may check out my previous post where I shared simple example of facebook iframe app with new php-sdk API. That would be good starting point if you are not familiar with facebook app development yet. And here is example app which uses this offline access permission.

This article uses $facebook object in examples. So before trying any of this out, create new facebook instance at the beginning of the script. It should look something like this.

//add php-sdk
require './facebook.php';

//Create facebook instance.
$facebook = new Facebook(array(
  'appId'  => 'application ID',
  'secret' => 'application secret',
  'cookie' => true,
));

Authorising url

First we need user to accept off-line access. When creating authorise url for your app, add 'offline_access' permission along others. This will grant permission to make such calls. This specific url is just a example but important part is here is req_perms parameter.

$loginUrl = $facebook->getLoginUrl(array(
	'canvas' => 1,
	'fbconnect' => 0,
	'req_perms' => 'publish_stream,offline_access',
	'next' => 'APP CANVAS URL IN FACEBOOK',
	'cancel_url' => 'URL WHERE TO REDIRECT WHEN ACCESS NOT GRANTED',
));
If using newer verions of facebook PHP SDK (v.3.0.0) (and up) use next one instead. Notice, that req_perms changed to scope
$loginUrl = $facebook->getLoginUrl(array(
	'canvas' => 1,
	'fbconnect' => 0,
	'scope' => 'offline_access,publish_stream'
));

Getting the token

If session is established, you can obtain it from session variables. That is all. Now you can store it in database or wherever you like and use it in your script when needed.

//get session
$session = $facebook->getSession();

//print out token stored in session
//using this you can do api calls even if
//user is not currently interacting with your app
if ($session) {
	echo $session['access_token'];
}
And if using newer verions of facebook PHP SDK (v.3.0.0) (and up) use next one instead
$user = $facebook->getUser();
if($user){
	echo $facebook->getAccessToken();
}

Using token for posting

Now the actual offline posting part. This is very simple. You only need that token gained earlier. This example shows how to post message on user's wall and get user's data. Also $res variable (array) will hold post ID if successfully posted. Code would be following.

//create message with token gained before
$post =  array(
	'access_token' => 'TOKEN HERE',
	'message' => 'This message is posted with access token - ' . date('Y-m-d H:i:s')
);

//and make the request
$res = $facebook->api('/me/feed', 'POST', $post);

//For example this can also be used to gain user data
//and this time only token is needed
$token =  array(
	'access_token' => 'TOKEN HERE'
);
$userdata = $facebook->api('/me', 'GET', $token);
Done! Nothing to add.

No gravatar aivable
Gayathri #
Excellently described. Thank you very much for post
No gravatar aivable
Bilal Ahmed #
Hi, Thanks you for such detailed tutorial, But I'm new to facebook development and i'm little confused on last part.

How do we actually post message on user wall? the line "$res = $facebook->api('/me/feed', 'POST', $post);"
will only store some data returned by api. Can you please explain little more with some more code sample.
No gravatar aivable
Bilal Ahmed #
OMG it was so simple.. :) Million Thanks buddy...I was searching it for days......... Amazing Tutorial...
No gravatar aivable
Balkini #
extraordinary tutorial ... it is so helpful
No gravatar aivable
Edd #
Hello, how can I contact developer here, who wrote this post?!? We need something like that developed and are looking for someone, who can do this )app for posting on useres wall, who has confirmed, taht we can do so). Please contact me by answering to this post. Thanks
Steinar #
This kinda works but user only stays logged in for maybe 10 minutes, and then I get ...

"Fatal error: Uncaught OAuthException: Error validating access token. thrown in facebook.php on line 543"

Any ideas? Do I need to store the "&expires_in=0" from the access_token somewhere?
No gravatar aivable
Steinar Knutsen #
I got this working beautifully! Thanks so much for sharing!
No gravatar aivable
sivakumar #
Hi , I want post the message to my fan page wall. Can u Please send me the code to post the message in the fan page wall, I am in great need of it. Thanks in Advance...
Janar Jürisson #
to sivakumar:

I think you can do it using "/YOUR_PAGE_NAME_OR_ID/feed" instead of "/me/feed" when posting used in my example.

Replace YOUR_PAGE_NAME_OR_ID with your page ID or alias.

So posting query becomes something like this:

$res = $facebook->api('/YOUR_PAGE_NAME_OR_ID/feed', 'POST', $post);

No gravatar aivable
sivakumar #
Hi Janar..

I tried both the things ..But it's not working.. I have send u the code Pls check it.
Janar Jürisson #
Ok, I dug a little bit into it. Seems that it's not so easy. It takes some extra rights and steps to do that.

Check out article http://developers.facebook.com/docs/authentication/ There is a subheading "Page Login". I would start there.
No gravatar aivable
sivakumar #
Hi, i tried the above code ..It's works superbly..The Tutorial was so nice ..Keep it Up...

Now i want to post the image in the wall. Can u Please send me the code ...Thanks in Advance.
Janar Jürisson #
Check out http://developers.facebook.com/docs/reference/api/post/ subheading "Publishing". There is a answer which properties you can send or get.

Something like this would work ...

$post = array(
'access_token' => 'TOKEN HERE',
'picture' => 'picture url here',
'link' => 'url',
'name' => 'title',
'caption' => 'caption',
'message' => 'message',
'description' => 'description'
);

$res = $facebook->api('/me/feed', 'POST', $post);
No gravatar aivable
avlon #
Thanks for this explanation which was very helpful!

I have a question, everything works fine but the content that i add to facebook via php (wall post, new albums, images, etc.) are all only visible by me. Does someone know why ?

No gravatar aivable
Gaurav Agarwal #
Can anyone help me, explain how do i fetch all the status of a person. I have the access token and offline permission is activated. I just need to know the api call.
No gravatar aivable
Majo #
Thanks a lot... It helped me...
{ Web-Farmer} #
Hi author,

This post helps me a lot ..

Information is very clean and neat.

Thanks
{ Web-Farmer }
No gravatar aivable
pushE #
Plz someone help I am getting the following error

Fatal error: Uncaught OAuthException: (#15) The method you are calling must be called with an app secret signed session thrown in______
No gravatar aivable
tzook #
a little question, this code works only when the user enters the script.

As in the code : "/me/feed/"...

that meant that the user entered the script gets msg 2 feed.

I want to make an script that will run weekly, and than post on the user's feed, without the need of him to enter the app.

how to run the script weekly is no prob, but how to post to the offline user is.

PLEASE help...

thanks Tzook
Janar Jürisson #
to tzook: That token you get from session must be saved somewhere so later your weekly script can access it and use it to post on token owners wall. I believe that's it. Haven't tried it for a while dough.

I hope it helps :)
No gravatar aivable
phil #
have you found a way to use more than one access token at a time in an array?

I am trying to create a cron that updates multiple users status' using the access tokens I have stored in mysql.

I feel that modifying something like this would be where to start:

//Retrieve user access_token from database
$results = mysql_query("SELECT access_token FROM demographic ORDER BY access_token ASC");
while($access_token_array = mysql_fetch_assoc($results)) {
$list_access_token[] = $access_token_array['access_token']; // to store results in an array
}
$comma_separated = implode(",", $list_access_token);
//print_r ($comma_separated);

//Array to post to wall
$post = array(
'access_token' => $comma_separated,
'message' => 'This message is posted with access token - ' . date('Y-m-d H:i:s')
);

//Actual post to wall
$facebook->api('/me/feed', 'POST', $post);

any suggestions would be appreciated.

thanks a lot.
No gravatar aivable
smiles #
I could I use this to post on the users wall weekly? I've looked EVERYWHERE and I just can't find anything close enough to help me :(

I considered using php if, [like if( thursday = post on wall, else don't] sort of thing. but It would have to be open to know wouldn't it?
Janar Jürisson #
To phil, I am not sure that you can do that.

To: smiles, Use cron for that.
No gravatar aivable
Filipi #
Good morning , 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={uid}"));

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 . "";
}
?>
No gravatar aivable
Filipi #
Good morning , 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={uid}"));

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 . "";
}
?>
No gravatar aivable
urvisha #
i m not getting $session..
No gravatar aivable
Urvisha #
can you put download link for php-sdk.
bcoz i am not getting $session .please help me.
Thnxx.
No gravatar aivable
S.Sivakumar #
Hi Janar,

I want to develop a simple gift app . When the user selects a friend and send a image . The selected image should be posted on the sender and receiver wall. Do u have any idea about this . It will be so useful for me please help if u know . Thanks in Advcance
No gravatar aivable
phil #
Heres how to do it with a cron job if you have the access tokens stored in a mysql database:

$token,
'message' => 'message here.'
);

//Actual Post
$facebook->api('/me/feed', 'POST', $post);
}
?>
No gravatar aivable
Peter #
I have your last script being executed, token coming from an MYSQL database. Unfortunately I get "PHP Fatal Error: Uncaught OAuthException: Bad signature thrown in php-sdk/base_facebook.php on line 998". Can't find anything on Google that helps. Can you give me a hint please? Thanks!
No gravatar aivable
hai #
hi when i use the "me" it means that i am trying to post on my wall

i manged it to work only for posting in my wall ??

can you help me ??
Janar #
to hai: Not exactly. You are using access token to tell API whose wall to post.
No gravatar aivable
hai #
ok so i will use this sentex but

where do i put the code (php script)

in cron_job ?

tnx for the help
No gravatar aivable
Lukas Kupka #
Janar pls explain me the access token purpose. You wrote "You are using access token to tell API whose wall to post." but i thought that the AAAA in "/AAAA/feed', 'POST', array ...." tells api whose wall to post. For posting on users' wall i use access_token taken from this url:

https://graph.facebook.com/oauth/access_token?client_id=" . Conf::$FB_APP_ID . "&client_secret=" . Conf::$FB_APP_SECRET . "&grant_type=client_credentials
Janar #
I think my explanation is little bit confusing. What I mean fallowing. If I want to post on users wall when he is not interacting with my application currently, I have to use access_token provided earlier by that user. There is no need for "/AAAA/feed" where AAAA is user because when using that token given earlier, API acts like being that user itself. I can't explain it better at moment. Maybe it helps.
No gravatar aivable
Lukas Kupka #
I think I've got it. You explain me clearly what i want you to and really appreciate what you've done here for fb developers. THNX
Fabrizio #
Hi Janar,


very helpful! I am going to store the token in DB but I cannot find what the length is... do you know if there is a maximum access_token length stated in the OAuth 2.0 specification. I haven't found it yet.
Janar jürisson #
Actually I don't know. And if I look around I only see same questions all over the google. Don't know is it true, but here it says its not defined at all. I currently use varchar 255 @ MySql (since there has not been problems with that), but sure I should investigate that someday myself too.
No gravatar aivable
Say Hong TAN #
Hi Janar! Great tutorial!

I was going through the code but found that the 'cookie' parameter needs to be disabled, otherwise authenticating with facebook doesn't work.


'application ID',
'secret' => 'application secret',
// 'cookie' => true,
));
?>

I'm using Facebook PHP SDK 3.0.1
drooh #
Janar, thank you so so much for writing such an easy to understand tutorial. I really wish that everything out there was this easy to follow. I spent so much time going through other tutorials and they were way to complex.

Have you made a tut similar to this for twitter and php?
No gravatar aivable
bRy #
Hi Janar, I would like to post to a fan page. How can this be done?
Janar jürisson #
to Drooh: Thank you. I haven't done Twitter or PHP tutorials :)

to bRy:
I haven't done it myself yet. So you probably are better off by googling around a bit. I am almost sure it is very much discussed topic.
No gravatar aivable
Leandro #
hi, thank you very much for the post!
I have a problem ..

$ token = array (
'access_token' => 'TOKEN HERE'
);
$ userdata = $ facebook-> api ('/ me', 'GET', $ token);


This code creates me a 500 error on the server, it can be?
I'm trying to get information from a user with a token.

Thanks
No gravatar aivable
Arjan #
great tutorial. But I found out something strange when you post a link to your wall, while using the offline_access permission.

The link is posted on the wall, no problem there. But when you click on it nothing will happen. If another FB user is clicking on that link facebook is asking that user to give offline access to the app?

Does anybody have an idea how to prefend this?
Janar #
to Arjan: I find it not strange. It's like it should be. If you are talking about "via your app name" link?

Its up to you what you display for user who accesses your application. For people who have not allowed you app yet it will ask permissions and its normal.
No gravatar aivable
fb_beginner #
is it possible, to post on user's wall by using the app/page id? (like, my app will post on the user's wall...)
Janar #
to fb_beginner:

Yes- trough app it's possible. Current blog post is one example of that.

But trough page- as far as I know it's not possible. Also not seeing such token @ http://developers.facebook.com/docs/reference/api/permissions/
Mohammad Shahid #
It is strange for me that we can post offline on facebook wall.

very easy and useful post, thanks alot :)
No gravatar aivable
Yuri Cauna Robles #
Muchas gracias! Todo muy Claro! gracias n.n
Thanks! all it's Clear!
No gravatar aivable
masoom #
'my ap id',
'secret' => 'my sec',
'cookie' => true,
);
$facebook = new Facebook($config);
$facebook->getLoginUrl(array(
'canvas' => 1,
'fbconnect' => 0,
'scope' => 'offline_access,publish_stream'
));

$user = $facebook->getUser();
if($user){
$mytoken=$facebook->getAccessToken();
}
$post = array(
'access_token' => $mytoken,
'message' => 'This message is posted with access token - ' . date('Y-m-d H:i:s')
);
$res = $facebook->api('/me/feed', 'POST', $post);
?>


Hello this is my code but its not run while i use offline_access ,but i get the access token its mean the $facebook->api('/me/feed', 'POST', $post) does't work please someone help me its urgent
Janar #
Your question is confusing. It's hard to tell what is your exact problem here. But I see you are not doing anything with string returned by getLoginUrl() method. You should create a link with that URL and fallow it.
No gravatar aivable
Petr #
Hello,
I would like to post on the company wall but the script still posting on my wall. The company wall is still empty.

How can i grand privilegies to to application, to posting on my wall? I filled /COMPANY_ID/feed (replaced COMPANY_ID), but still posting on my wall.

Could you give me some help please?

Thank you
Janar #
Check out my comment @ http://eagerfish.eu/using-facebook-off-line-access-to-post-on-users-wall/#comment-227
No gravatar aivable
masoom #
hello friend i want to auto wall post by using cron job in my previous code that is working for offline_access,there my wall posting does't work can u tell me how i get specific error through from facebook that helps me about the problem
No gravatar aivable
masoom #
hello janar plz send me auto wall posting complete code where i just change my appid and secrete and its run through cron,if u r easy then plz send me by email on masoom.ego@gmail.com
No gravatar aivable
masoom #
hello my all working is done but still post method does't work while i get offline_access and also get the access token..
here is my code
$facebook->api('/me/feed', 'POST',array('access_token'=>$access_token,'link' => 'www.funmx.com','message' => 'myposting'));
No gravatar aivable
Petr (from 13 January 2012 19:48) #
Hello,

I looked on the autorization.
Everythink is ok, but when I admin more company pages, I dont want to grand privileges to all this pages.
Is it possible to choose one, where can I post on the wall?

Thank you much
No gravatar aivable
harold #
hello experts,

im getting errors on my log message
OAuthException: Error validating access token: Session has expired at unix time (number) . The current unix time is (number).
ive readarticles about this and i found out FB team are makingchanges with there apps. and ive read, the error is when a user is offline
everytime i make a job i get this
how can i edit FB apps so it can post to offline users
thanks
No gravatar aivable
Andras #
Hi the code works fine, but my only the problem is I can see only the wall post if I go to my friend profile, it doesn't appear in the news, it does in the right corner but not in the main news, any idea why? I have tried everything now I just don't know what could be the problem.
I am co-founder of web/media studio GIVE me. and (android)developer at start-up named Choco. Read my about page to learn more.