Example of facebook app which uses offline access permission

Important notice! There was change in API in May 1, 2012. "offline_access" permission was deprecated. Quote: "For existing apps, there are no changes required for your app, but you should consider using the new endpoint". I have to re-write or add fallow up articles to my posts about "offline_access" permission about that suggestion/change. I also have to modify my example and live apps. But AFAIK - there is no hurry, because nothing gets broken that day. Read more about it here

Facebook iframe example app - batch posting (poster.php) This example is written using facebook PHP SDK v.3.0.x

I decided to refresh my knowledge of developing facebook apps. API and PHP SDK has been changed somewhat since my last time I used it. Had to update my previous posts also. I decided to create simple app that collects users access tokens (with offline_access) into mysql database and later uses these to post on their walls. I chose it because lot of people were asking me about this and I need it too soon. I will not explain lot- just download the package and read comments in code. Should be straight-forward and easy to fallow.

Check it out

This app is published at moment. Feel free to check it out or download the source code and start playing. It is also aivable at github. In my working example I use cron to fire "poster.php". There is no self-timer what people have asking about.

Files in package

In this exsample I use only 3 files. config.php, poster.php and index.php.

config.php Needs no comments. Just Fill in. Variables there should be pretty self explanatory.

index.php This collects the access tokens provided by the users. It displays authorising link. After user accepts to give permissions it saves access token into database. For simpler start I included table creation into script- so it will be created automatically (if your mysql user has CREATE permissions).

poster.php This is where real action takes place. It has simple form with some fields. This fields make up post that will be sent on each user's wall after submitting. Afcourse there should be more things covered like token check to remove old and not working ones. But I let you to handle these yourself to keep main code clean.

Set it up

In this post you can read about setting up your iframe application in facebook. It should be fairly simple. You also need to download latest 'facebook.php' (php-sdk) from github and place it next to index.php. Now you should be ready to go.

No gravatar aivable
Andrey #
I have the same code (almost) but without getUser() function. I post on friends wall and the only option I have is saving tokens, posting and cleaning tokens from my DB for security reasons (just in case).

It worked fine until Facebook displayed a message saying that token is expired and they decided to change it for security reasons. We are going live with our software on 20th. I hope no surprises will arrive.
Janar jürisson #
Thank you for your info.

I think my example is out of danger. At least if we are talking about http://developers.facebook.com/blog/post/520/ this change. PHP SDK was already updated when I wrote this example.

As I see you only need to update your PHP-SDK and should be fine. But we will see. I will dig into it if something brakes.
No gravatar aivable
Andrey #
There are two things that bother me:

1. Why should I save token myself in the database? It does not follow any logical scenario. If Facebook has a possibility of offline posting, why don't they have a mechanism of secure token storage? It is a bug in design of the offline postage feature or it is not allowed at all. But if it's not allowed, why do they have the offline option at all? :)
I don't want Facebook to ban my application in the middle of campaign - this is my main fear.

2. Do they usually care about backward compatibility? Should I care about same-day-release of the Java SDK and my product? They don't have early SDK preview, do they?

Thank you
Janar jürisson #
1. Actually, I don't understand exactly what you are referring to. And also I think app banning is not relevant to current post topic.

2. I have not used FB API deeply to confirm it. But over last year I had to modify my app 2 times to get it working with latest PHP SDK.
No gravatar aivable
Andrey #
Here are some results for you if you interested.

- 1 testing Facebook account
- 16 real posts in database
- Copied the 16 rows to 512

- Cron executed in 59 seconds (submitted successfully)
- Posts continued showing up on the testing account for another 3 minutes
- 161 finally displayed under the account.
- 351 posts are lost

We are not going to post multiple posts to one person, but one post per person. I hope this is the problem of missing posts.

Thank you for your help!
No gravatar aivable
Lucas #
thanks a lot man, i really appreciate your fb-related posts!
No gravatar aivable
BigBee #
Good stuff. Your contributions are much appreciated.
No gravatar aivable
BigBee #
Here is a link to a blog post with code on how to Refresh lost access_tokens.
No gravatar aivable
Andrey #

My application collects posts from people willing to surprise their friends at specific times. The application runs for four days already. Two days out of the 4 operated fine, but other 2 returned "OAuthException: (#210) User not visible".

Did you try to delay your posts as long as 20 hours and more?

The offline access is unlimited in time, as I understand.
No gravatar aivable
Alexandre de Deus #
Hi Janar.

Your articles are really the best I've found talking about facebook apps. I'd like know if you can help me, I need change this scripts to post the message in the wall automatically, just after user authorization, and store the user's email and phone.

Thanks in advance.
Janar jürisson #
to Andrey: http://developers.facebook.com/docs/reference/api/permissions/ read offline_access description there. It should answer your question. But I have not tested this 1-2 days later. Probably soon I'll need it in one of my works sos I can test it.
No gravatar aivable
Zoelfikr (its me again) #
1. Can we make delay between post without cron? it is like counting down at rapishare or mediafire link download :) i belive it can, but i dont know to figure it. (i just googling and find the tutorial how to make counting link download like at rapidshare but i dont know to figure it.

i think in this line we can insert that code:

$output .= "Posting message on '". $row['name'] . "' wall success";
} catch (FacebookApiException $e) {
$output .= "Posting message on '". $row['name'] . "' wall failed";

2. Can we make a progress bar/percentage so we know how much time the progress post ongoing (in the same page)

3. The authorize page for user in this script is going to "www.facebook.. bla.. bla.." can we make a modified so if people that access the app from mobile phone so it will deliver to "http://m.facebook" i found it in this line: "if(!$user){$loginUrl = $facebook->getLoginUrl(array".. bla.. bla.. :)
No gravatar aivable
Mirza Ali Nasrullah Khan #
Thanks Buddy u rock....!!!
No gravatar aivable
Lorenzo #
Hi Janar,
I've noticed that the posts have the same "submitter" as the destination user. Do it is possible to post a message but "appearing" as if the FB App wrote it ? (with app icon and name).

Janar #
Hi Lorenzo,

Are you sure? My example should post as application not as acting user. There are "via APP NAME" below the posts. Are you talking about something else? Maybe you are talking about posting as "facebook page"?
If so- you need some extra work (but still this example can be base for that). Bu I haven't done it myself yet, therefor I can't help with that.
No gravatar aivable
Lorenzo #
Thank you Janar.
Yes I'm looking for posting as "facebook page" or "facebook application" entity like some FB games do on user's feeds.
With your example the app generates a message like if the user write himself in self feed.
If someone can advice is wellcome :-)

thanks again.
No gravatar aivable
Lorenzo #
Uhm looking better I'm wrong. All FB Apps publish on user's feeds as if the use is writing himself....

No gravatar aivable
Joe #
Wao! This works like charm

@Janar, I wanted to be able to count friends of users with this:

How can one use this to count the number of friends?
I'm very new to facebook API

Can you help please @janar ?
Janar #
I know it is possible to get friends list. So You could get total count based on that.

Look my other example @ https://github.com/janar/facebook-php-sdk-example-app/blob/master/index.php

Find the row:
$friendsTmp = $facebook->api('/' . $userData['id'] . '/friends');

Friends count would be there count($friendsTmp)

You could use also $facebook->api('/me/friends'); to get current users friends.

Look this page too http://developers.facebook.com/docs/reference/api/ for other endpoints in API.

No gravatar aivable
Hays Tome #
Who will use this application?
The application developer or user application
I ask how the application developer can be pasted on the wall of users
No gravatar aivable
Lina #
gr8 one:) Thanks alot...I just want to ask when I open poster.php and post a msg it tells me that Posting message on 'username' wall failed! why!what's wrong I did!
Janar #
I can't clearly answer due lack of information you provided. But It probably failed because access token provided was wrong.

Try to change

$output .= "Posting message on '". $row['name'] . "' wall failed";

line to

$output .= "Posting message on '". $row['name'] . "' wall failed because of :" . $e->getMessage() . " ";

And it should tell you what is wrong.

There is also change in FB API- offline_access token is actually deprecated - probably it might have some effect - I have not tested it yet by myself. But soon I have to because of my facebook offline access posts in this blog :)
No gravatar aivable
Lina #
Thanks for your fast reply..I changed the line and the output was:wall failed because of :Error invalidating access token: Session has expired at unix time 1336302000. The current unix time is 1336305256.
Any idea!
Janar #
Exactly what it says- access token used is expired- you need to get new one :)

Where did you get the initial access token?
Do you have set up this code somewhere?

If I don't know the context it's hard to guess things.
No gravatar aivable
James C. #
can you also make tutorial in making a script/site where users can get like using the entered access tokens?
something like this:

No gravatar aivable
py #
I got this error messag:
API Error Code: 191
API Error Description: The specified URL is not owned by the application
Error Message: Invalid redirect_uri: Given URL is not permitted by the application configuration.

How to fix it? thx
No gravatar aivable
py #
Hi Janar,

Thx a bunch for your reply. I have fixed error 191. But i got another error message like this,

Secure browsing is not supported
This application does not yet support secure browsing (HTTPS).

should we have a https url?
No gravatar aivable
jonathan #
I'm trying to get more but not save the token in the database .
would show me better. I am Brazilian I am using google translator
Janar #
Py: Yes- it's actually I don't really know for sure because I have not been done any apps after 1 October when that went mandatory. Read more @ http://www.facebook.com/EagerFish/posts/238605112856372

jonathan: Nothing much to show- download/view package in github and you can see. Can't get much easier.
No gravatar aivable
Yossarian #
Hi Janar!

At first thx for the source. I just downloaded your code and tried it, but $facebook->getUser() always return 0. What can cause this problem?
No gravatar aivable
Janar #
I am not sure what you should check. Maybe this is related to the deprecation of the offline_access token. Newly created apps might not work- but also I am not sure because I have not tried to make new app and use this offline_access token. I have added a notice on top of my post to indicate this problem. I try to deal with things in this summer, but not yet.

You should consider using another endpoint way to make this work. There is a link in notice on top of this blog post.
No gravatar aivable
Yossarian #
Thx for your reply. I think I took some mistake when i install your code. When I call the index.php it ask for rights to facebook account, but it did not run into that part of code witch begin with "if ($user){" like your application when i install it.
No gravatar aivable
kryshac #
how to increase access token during
No gravatar aivable
Ahmed #
Hello sir how I can do this only one time when user allow apps to send to his wall only one time?
No gravatar aivable
mallika #
user_id='" . mysql_real_escape_string($userData['id']) . "' AND
id != '" . $row['id'] . "' In this mysql query why are you deleting from offline_access_users.How is 'id' column different from 'user_id' column in your database
Janar #
I can't remember why I was concerned to add this deletion part into script to make sure that there is only one access_token for each user. It can't happen so this deletion should be removed.

Currently it relies on my local "id" field. Can be re-written to rely on facebook id instead.

I have been thinking about updating this script but have no time in hand. Could remove AUTO_INCREMENT "id" column and rely on facebook given "user_id" instead.
No gravatar aivable
samir #
please help
how i can do "like" in behalf of the users who authorized my app ??
Janar #
How about trying google one in a while?

First answer to your question says it's not possible - http://stackoverflow.com/questions/5837010/liking-a-page-on-behalf-of-a-user
No gravatar aivable
Diego #
Hi, Janar.

Congratz to your app. It's incredible.
However, I wonder if it's possible add a timer to it, in order to avoid errors in database's biggest.
No gravatar aivable
shreef #
i have 40k member on this app
thanks to you
but there is problem
i should wait about 11 hours to complete the post :D

please send me if you have answer
shrmony (at ) gmail.com
No gravatar aivable
Verlon #
I don't recive any posts from 5 to 5 minutes, on my wall. Do I miss something, or it needs an update. I think is a great app in specialy poster.php except, When user log into the app, in time of about 1-2 hours I am able to send him wall posts, but after that i get only "Posting message on 'User' wall failed". I'm not an expert, but it is possible to be from access_tocken ?
I realy want to make this app work for me to.
Janar #
There is update in API- and I have not updated my examples to new endpoint. (That's why I have notice on top of my post) If I remember correctly now you have to update access_token regularly. Without that it will expire.
No gravatar aivable
Verlon #
Still I don't recive test posts from 5 to 5 minutes. Do i miss something. I have tested your app url and is working good i recive messages every 5 minutes.
No gravatar aivable
Verlon #
I made the api update for the new endpoint. poster.php is working right. But how does it post from 5 to 5 minutes. Where do i set this interval. I am sure this app http://apps.facebook.com/offline-access-dmo/ is not the demo, is different from the one you gave it to us.
I really want to make it work like the one you say is the demo.
Janar #
I quote my post: "In my working example I use cron to fire "poster.php". There is no self-timer what people have asking about."

I use CRON job to make my 5 minute example to work. The code is actually the same. But what fires it- is different.
No gravatar aivable
thailandy #
hi janar
thanx for this goood tot
my ask how you used cron in poster.php
i used in my own site but not work ??? i used cron job to poster.php but no post in wall ??? can you pls tell me what you use in poster.php ????
No gravatar aivable
RobertVudge #
Привет всем участникам форума! Класный у вас сайт!
Что скажете по поводу этих новостей?
Ещё тут много интересного: самая высокая точка донбасса http://enewz.ru/
No gravatar aivable
Joshua Storkey #

My name is Sergey and I am a founder of Sweaty Quid Freelancer Market place where you are able to purchase and offer all kinds of on-line solutions varying from backlinks and guest post to explainer video clips, infographics and write-ups for your web site.

I believe that you and your website eagerfish.eu could seriously benefit from Sweaty Quid, no matter if you want to offer your services or hire freelancers to aid you to grow your company.

I have been a freelancer on numerous market places for in excess of 5 years and have had my accounts arbitrarily closed down, my earnings pocketed and I just simply had a hard time with lots of low quality freelancers. After much unnecessary aggravation, I decided to start my very own freelance marketplace that would do things differently and much better.

After almost one year of caffeinne powered nights, myself and my crew at Creative Bear Tech have developed Sweaty Quid from groun up. One month into our launch we have managed to bring in a really good number of high quality freelancers and an exceptionally high number of repeat customers. I believe this functions as a testament to our excellence.

Sweaty Quid is a spam-free and straightforward marketplace for high quality freelancers and buyers. We are rigorously banning all spammy vendors who do not pass our quality threshold and leave only the absolute best ones. Keeping up with the latest technologcal developments, we also take cryptocurrency as one of our payment methods. Our ethos that defines us is that sometimes less is more, especially when it comes to high quality freelancers.

We are still very new in contrast to other freelance marketplaces, but we are already punching above our weight.

I would like to welcome you personally to join Sweaty Quid Freelancer Market Place!

Kind regards

Sergey Greenfields
Founder of Sweaty Quid Freelancer Marketplace
Flat 9, 1 Jardine Rd, St Katharine's & Wapping,
London E1W 3WD, UK
No gravatar aivable
카지노사이트 #
In which case you have to be able to compliment their non-physical attributes as well, such as their “sweet voice” or “beautiful soul” or “warmth.” etc…..But, look here, in truth there are no special rules on these things. Almost every human being/ every girl has some qualities that can be complimented and very few people are immune to flattery.
Just find those beautiful attributes in your subject of interest and comment about them. You will usually elicit a positive response because it will be a true comment.
No gravatar aivable
바카라사이트 #
Everyone is like, girls need to be complimented, gifted regularly, taken out on dates and shopping etc wished on birthday/anniversary etc. Well to tell you the truth this is not exactly what we want.
So, if you value their presence, treat them like a human being with feelings and be careful even a little bit you don't have to do all the valentiney stuff. It's feeling that matters the most.
No gravatar aivable
카지노 #
However, if you do value them and also give them a little bit of a surprise (outings/shopping/gifts) it would always be like cherry on the cake!
A girl likes the comment that is the most sincere and least superficial. Stay away from beauty as an overall concept though a spontaneous utterance that you really like her hair, or smile, is likely to be well received.
No gravatar aivable
바카라 #
Appraising their look will always melt anyone other then that when it's come to comparison girls always wants to be the best in her own way.
You can say that you are unique and more good then anyone else or specific person that might work more.
No gravatar aivable
카지노사이트 #
Apart from that, girls need natural logical comments in most of the cases. Do remember about that also.
Girls mostly like compliments (just replacing word comment because comments are more like tagging them with somthing stupid) about their qualities. Like if she is artist tell that she is really creative her arts expresses something.
No gravatar aivable
Adele #
It's amazing to vissit thks web site and reading the views of all friends regarding this paragraph, while I am also zealous of getting
азартные игры играть бесплатно и без
регистрации играть азартные игры без регистрации бесплатно
No gravatar aivable
Adele #
It's amazing to vissit thks web site and reading the views of all friends regarding this paragraph, while I am also zealous of getting
азартные игры играть бесплатно и без
регистрации играть азартные игры без регистрации бесплатно
No gravatar aivable
Terrell #
I visitdd many blogs butt the audio qality for audio songs current at
this web page is truly superb.
maeng da thai kratom capsules
maeng da thai kratom capsules
No gravatar aivable
Erik #
Hi theree would you mind stating which blog platform you're working with?
I'm looking to start my own blog soon buut I'm having a difficult
time making a decision between BlogEngine/Wordpress/B2evolution and Drupal.
The reason I ask iss because your design and style seems different then most blogs and I'm
looking for something unique.P.S Sorry for bekng off-topic but I had too ask!


web site
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.