In this post you will learn how to post to Facebook page wall (Not User Wall) using PHP and Facebook API. To understand this article you must have knowledge of Facebook application development and their API usage. Before we begin I assume you have created Facebook Application and you have a running Facebook Page where you want your message to appear.
Basically we have three PHP pages in this tutorial. Configuration file (config.php), Form Page (index.php) and Process Page (process.php). Index page is a HTML form with message box and list of user pages, where user selects a page and post some messages, which gets posted to process.php, if everything goes well, it shows a success message and user message will appear on Facebook Page wall. Other files such as Facebook PHP SDK, css file etc are included in sample download file.
Configuration
Config.php stores variables, such as facebook Application ID, secret, return url etc. Change these settings with your own. Notice include_once(“inc/facebook.php”); , inc folder contains Facebook PHP SDK files, which can be downloaded from https://github.com/facebook/php-sdk, but I have already included these files in downloadable zip file at the bottom of the page.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | <?php include_once("inc/facebook.php"); //include facebook SDK ######### edit details ########## $appId = 'xxxxxxxxxxxxxx'; //Facebook App ID $appSecret = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxx'; // Facebook App Secret $return_url = 'http://yoursite.com/script/process.php'; //return url (url to script) $homeurl = 'http://yoursite.com/script/'; //return to home $fbPermissions = 'publish_stream,manage_pages'; //Required facebook permissions ################################## //Call Facebook API $facebook = new Facebook(array( 'appId' => $appId, 'secret' => $appSecret )); $fbuser = $facebook->getUser(); ?> |
Front Page
Index.php contains a message form for this demo, user is redirected to facebook authentication page, where s/he is required to authenticate and grant mainly two extended permissions publish_stream and manage_pages. It seems permission manage_pages is required to read user pages, and to post on page wall, application requires publish_stream.
Once user grants these permissions, user is redirected back to index page, where s/he is presented with a form containing a message input box and list of his own Facebook pages. You see, to list user pages, I have used FQL (Facebook Query Language), FQL is Facebook’s own query language and it is very similar to MySQL queries, with FQL it is possible to retrieve more information in a way that we can’t with just Graph API (we will get back to it soon). On form submission the data is sent to process.php.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 | <?php include_once("config.php"); if ($fbuser) { try { //Get user pages details using Facebook Query Language (FQL) $fql_query = 'SELECT page_id, name, page_url FROM page WHERE page_id IN (SELECT page_id FROM page_admin WHERE uid='.$fbuser.')'; $postResults = $facebook->api(array( 'method' => 'fql.query', 'query' => $fql_query )); } catch (FacebookApiException $e) { echo $e->getMessage(); } }else{ //Show login button for guest users $loginUrl = $facebook->getLoginUrl(array('redirect_uri'=>$homeurl,'scope'=>$fbPermissions)); echo '<a href="'.$loginUrl.'"><img src="images/facebook-login.png" border="0"></a>'; } if($fbuser && empty($postResults)) { /* if user is logged in but FQL is not returning any pages, we need to make sure user does have a page OR "manage_pages" permissions isn't granted yet by the user. Let's give user an option to grant application permission again. */ $loginUrl = $facebook->getLoginUrl(array('redirect_uri'=>$homeurl,'scope'=>$fbPermissions)); echo 'Could not get your page details, make sure you have created one!'; echo '<a href="'.$loginUrl.'">Click here to try again!</a>'; }elseif($fbuser && !empty($postResults)){ //Everything looks good, show message form. ?> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Post to Facebook Page Wall Demo</title> <link href="style.css" rel="stylesheet" type="text/css" /> </head> <body> <div class="fbpagewrapper"> <div id="fbpageform" class="pageform"> <form id="form" name="form" method="post" action="process.php"> <h1>Post to Facebook Page Wall</h1> <p>Choose a page to post!</p> <label>Pages <span class="small">Select a Page</span> </label> <select name="userpages" id="upages"> <?php foreach ($postResults as $postResult) { echo '<option value="'.$postResult["page_id"].'">'.$postResult["name"].'</option>'; } ?> </select> <label>Message <span class="small">Write something to post!</span> </label> <textarea name="message"></textarea> <button type="submit" class="button" id="submit_button">Send Message</button> <div class="spacer"></div> </form> </div> </div> </body> </html> <?php } ?> </body> </html> |
Posting to Facebook Page Wall
After receiving page id and message variables from index page, all we need to do is use page id to select a page and send a POST request to PAGE_ID/feed with the publish_stream permission. This script tries to post message to selected user Facebook page wall, and displays a success message.
Main thing to note here in process.php is $post_url and $msg_body array variable, these two things define what you are going to post on Facebook page wall, for example you may want to automatically post notes, events, questions, status message, photos or videos.
The following snippet creates a status message :
1 2 3 | $msg_body = array( 'message' => 'message for my wall' ); |
To post a link on Facebook page wall :
1 2 3 4 | $msg_body = array( 'link' => 'http://www.saaraan.com', 'message' => 'message for my wall' ); |
Creates a note, but the $post_url must be PAGE_ID/notes.
1 2 3 4 | $msg_body = array( 'subject' => 'Subject of Note', 'message' => 'message for my wall' ); |
To create a poll question on behalf of the Page, $post_url to PAGE_ID/questions.
1 2 3 4 5 | $msg_body = array( 'question' => 'Do you like saaraan.com?', //Question 'options' => array('Yes I do','No I do Not','Can not Say'), //Answers 'allow_new_options' => 'true' //Allow other users to add more options ); |
To post a photo, change $post_url to PAGE_ID/photos.
1 2 3 4 | $msg_body = array( 'source' => '@'.realpath('myphoto/somephot.gif'), 'message' => 'message for my wall' ); |
You can also save your photos, notes, status messages as unpublished by issuing ‘published’=>’false’. Or set scheduled_publish_time for the post : ‘scheduled_publish_time’=>’1333699439′ (UNIX timestamp).
1 2 3 4 5 6 | $msg_body = array( 'source' => '@'.realpath('myphoto/somephot.gif'), 'message' => 'message for my wall', 'published' => 'false', //Keep photo unpublished 'scheduled_publish_time' => '1333699439' //Or time when post should be published ); |
Here’s complete code of “process.php“:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 | <?php include_once("config.php"); if($_POST) { //Post variables we received from user $userPageId = $_POST["userpages"]; $userMessage = $_POST["message"]; if(strlen($userMessage)<1) { //message is empty $userMessage = 'No message was entered!'; } //HTTP POST request to PAGE_ID/feed with the publish_stream $post_url = '/'.$userPageId.'/feed'; /* // posts message on page feed $msg_body = array( 'message' => $userMessage, 'name' => 'Message Posted from Saaraan.com!', 'caption' => "Nice stuff", 'link' => 'http://www.saaraan.com/assets/ajax-post-on-page-wall', 'description' => 'Demo php script posting message on this facebook page.', 'picture' => 'http://www.saaraan.com/templates/saaraan/images/logo.png' 'actions' => array( array( 'name' => 'Saaraan', 'link' => 'http://www.saaraan.com' ) ) ); */ //posts message on page statues $msg_body = array( 'message' => $userMessage, ); if ($fbuser) { try { $postResult = $facebook->api($post_url, 'post', $msg_body ); } catch (FacebookApiException $e) { echo $e->getMessage(); } }else{ $loginUrl = $facebook->getLoginUrl(array('redirect_uri'=>$homeurl,'scope'=>$fbPermissions)); header('Location: ' . $loginUrl); } //Show sucess message if($postResult) { echo '<html><head><title>Message Posted</title><link href="style.css" rel="stylesheet" type="text/css" /></head><body>'; echo '<div id="fbpageform" class="pageform" align="center">'; echo '<h1>Your message is posted on your facebook wall.</h1>'; echo '<a class="button" href="'.$homeurl.'">Back to Main Page</a> <a target="_blank" class="button" href="http://www.facebook.com/'.$userPageId.'">Visit Your Page</a>'; echo '</div>'; echo '</body></html>'; } } ?> |

The demo is not working.. Its returning error at the end.
The $permission variable is not using anywhere
this is very good site
the post in facebook page wall is showing in zipped format.i want it to look like a normal post on a wall please help me
the post in facebook page wall is showing in zipped format.i want it to look like a normal post on a wall please help me.i wnat to post in wall without loging to facebook
Thanks for this post and a great Joomla script.
this is a test comment for facebook
Fatal error: Class ‘facebook’ not found in C:Program FilesEasyPHP-5.3.8.1wwwLandshoppeconfig.php on line 13
the facebook.php is as follows;
window.fbAsyncInit = function() {
FB.init({
appId : ‘************************’, // App ID
channelUrl : ‘//www.landshoppe.com/Channel.html’, // Channel File
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
// Additional initialization code here
};
// Load the SDK Asynchronously
(function(d){
var js, id = ‘facebook-jssdk’, ref = d.getElementsByTagName(‘script’)[0];
if (d.getElementById(id)) {return;}
js = d.createElement(‘script’); js.id = id; js.async = true;
js.src = “//connect.facebook.net/en_US/all.js”;
ref.parentNode.insertBefore(js, ref);
}(document));
what’s going wrong ?!
You are getting the error probably because you have not included Facebook SDK files in specified folder, look at line in config.php
include_once(“inc/facebook.php”);
inc folder contains Facebook PHP SDK files, which you can download it here https://github.com/facebook/php-sdk
Thanks a ton Saran ! You are a life saver !
THANK YOU! THANK YOU! I have been trying for hours and hours to get posting to the page to work. Your code is the first thing that has worked.
I am having a problem though – it works great, posting to a page with just the message parameter, but if I try to post a link using the link parameter, then the post comes from the user, not the page. Why would adding more information to the post change who it is posted by?
OK, I figured it out, once you add other info, you also need to add the action parameter that’s in the code comments. Then is posts as the page!
‘actions’ => array(
array(
‘name’ => ‘Saaraan’,
‘link’ => ‘http://www.saaraan.com’
)
)
Thanks again – this is the best coding example I’ve seen.
Hi saaran,
Your code was really helpful.Thanks a lot and it works well!!!!!!!.Now my problem is i want to post stories without logging into facebook .i have included Facebook PHP SDK files..can you please help me ,i have asked these question in many forums but didnt get a clue,can you plz hep me in this
Hi, as far as I know, it’s not possible to post to Facebook wall without logging in, because Facebook requires active user session, it doesn’t allow anonymous posting.
Hi Saran,
But in wordpress we have plugin http://wordpress.org/extend/plugins/facebook-page-publish/ which has the provision to publish stories from wordpress admin to facebook page wall without loggin in to facebook directly.
humm.. may be you are right, I am sure there’s not much you need to modify in code above. there’s a post about it here : http://php-academy.blogspot.in/2011/04/how-to-post-from-facebook-app-to.html
Well, I thought it was posting as the page, but not quite. Here’s the facebook page: https://www.facebook.com/pages/CVHS-Connect-Volunteers/325543280870866
There are 3 posts, 2 created manually and the 3rd – the Manga Books one, created with this code. The problem is that the 2 manually posted items have the “Share” link at the bottom and the code created one has just a link to the page. We really want people to share these items, so it’s important that the share link it there.
Try changing $post_url to PAGE_ID/links instead of PAGE_ID/feed.
I get this after submitting:
(#200) The user has not granted the application the permission to automatically publish feed stories
not working !
not working !
Do not publish
After login, the wall post form doesnt display. Goes directly to $homeurl. Looks like $fbuser details are not being captured..can you tell me why this is happening ?
my $homeurl is http://www.landshoppe.com that is my website
I have solved my puzzle. All the fb scripts needed to be in a seperate folder called scripts. Index.php was clashing with index.htm
Hi all,
I am trying to integrate my apps as shown above nut it’s not working. actually demo is itself not working and m getting same error as demo.
Please help me it’s really urgent.
Thanks & Regards
Sheeshkamal
can you tell me what error message are you getting?
Same error as we adre geeting in demo.
Could not get your page details, make sure you have created one or you need to log in again!
Click here to try again!
i have done but finnaly receiving this msg. . ?
(#368) The action attempted has been deemed abusive or is otherwise disallowed
Hello,
is there any tutorial how to Post to User’s Wall (status or a link)?
Thank you
the code work good but the post appear only when i open the page from my account , what can i do to make the post appear for any friend like Demo
I have a error in the process.php when i send my message: (#368) The action attempted has been deemed abusive or is otherwise disallowed
Why appear this error?
Hey Saran, was working with this code, i have to say thank you very much, but suddenly as today the code doesn’t work because once I try to log in and returns, the form doesn’t show. It seems like i don’t get the $post_results thing and the $fbuser seems to be 0, do you know what may be happening?? demo works just fine. Thanks in advance
Hi Saran, thanks for this post. I downloaded your file and put it to test, but here I got a message about the certification:
Invalid or no certificate authority found, using bundled information
Can you help me?
Thanks!
hi I think facebook recently updated their SDK, you should update Facebook files from https://github.com/facebook/php-sdk
I really like your blog.. very nice colors & theme.
Did you create this website yourself or did you hire
someone to do it for you? Plz answer back as I’m looking to create my own blog and would like to find out where u got this from. many thanks
Figured it out about the sdk earlier, but thanks, was wondering if something was wrong with the code or trying to bypass security. Downloaded the sdk again from github out of pure rage and worked, thanks for your answer tough and also very thank you for the code
Hi saran,
I`m working on a FB app,for which i took your app as a reference copy to understand the authentication process.for some reason i`m not able to run your app,once the user gives permission to the app, it fails to redirect to the next page(specified in redirect_url).i can see that in the Url “_=_” is getting appended and even $fbuser($facebook->getuser()) is also returning zero. so can u help on this.
thanks in advance
when i clicked demo here i got the following errors in your server… correct that and delete this comment… i am using your script to check facebook post demo often and suggest people of this.
Warning: Unknown: write failed: No space left on device (28) in Unknown on line 0
Warning: Unknown: Failed to write session data (files). Please verify that the current setting of session.save_path is correct (/tmp) in Unknown on line 0
The code work to login. But When it post the messege show this message:
“Not Found
The requested URL /fb/publish_to_wall/ was not found on this server.
Additionally, a 404 Not Found error was encountered while trying to use an ErrorDocument to handle the request.”
hey your tutorial is grt and working fine for me..
but can u please tell me how can i get the access token from the facebook for user pages. so i can post their page.
thanx
if i want to attach image in this post (direct in facebook page post uploaded in page albums)? seems i need some more permisions fileUpload
Download don’t work….
Hi Saran,
I have been searching Google forever and tried many different scripts. This is the first one that has worked flawlessly for me. I just wanted to say thank you for your work.
Hi Saran! First of all, many thanks and kudos for this awesome and working app.
However, I am new to facebook app, and have one doubt.
How can the app post on user’s behalf(without the user being logged in), once the user has authorized the app?
Hi there, this code is great and I’ve built a timer into the page to automate and post results of an rss feed to the facebook page. Works a treat, but the login keeps timing out… Is there a way to lengthen the login time or disable it completely?
I hope you can help me
Hi Rob, can you post the code here…would love to see how you are using code and the timer..
http://www.landshoppe.com/
Would you mind sharing with us the automation code you’ve used?
Hi Rob, hope you see this (and hope you answer
)
I’m doing a project for school and a part of it is exactly what you say you’ve done with your page (automate and post results of an rss feed to the facebook page).
I was wondering if you could help me and manage to do the same with my page.
Thank you in advance for any answer of yours!
Hi there, on the page with the form, I’ve simply used this bit of code to submit the form:
document.form.submit();
I have scripted the message area of the form to import the contents of an rss feed, which in turn is a php script which randomises the order of the feed and just returns 1 result (or as many as you want). When the page with the form loads in, it automatically populates the message box with the contents of the rss feed and POSTs to the ‘process.php’ page which does the actual posting to your facebook page.
On this page, I simply put a timed re-direct back to the initial page using:
2
3
4
5
6
7
8
9
10
11
12
var redirect="index.php"
function countDown(){
if (count <=0){
window.location = redirect;
}else{
count--;
document.getElementById("timer").innerHTML = " "+count+" "
setTimeout("countDown()", 1000)
}
}
Hey presto, it automates and will post randomly selected items from your rss feed. You can even put a bit of code into the process page to randomly generate the time that the re-direct will occur…
My problem is still unsolved however… If the re-direct is too long, the process requires a manual re-login to facebook. If anyone knows any more about the timeout period and how to extend it, I would love to hear back from you
Regards
Rob
Hello, Cool Script. But on PHP 5.3.8 I always facebook api returns 0 on getUser method even when logged in.
hello,
i downloaded the zip file and configured everything.
i login as the “owner of the page” and can post status.
but if im going to login, as an another user, (not the owner) it throws an error “Could not get your page details!”
so i guess, only the owner can post a message on that wall?
Please advice. thanks.
I have installed the script which works fine for posting to the page, but when I change the post type to photo, I get an error: (#324) Requires upload file.
In researching, I found that maybe I should add the following to the config file:
//Call Facebook API
$facebook = new Facebook(array(
‘appId’ => $appId,
‘secret’ => $appSecret,
‘fileUpload’ => true,
‘cookie’ => true
));
That did not seem to change anything though. Can you provide me with some support on how this can be accomplished?
I can use the app to login the fan page but it does not allow me to post the message.
Error: (#368) The action attempted has been deemed abusive or is otherwise disallowed.
Any idea?
I find out the problem due to my hosting platform contains one hidden php file. When I remove it, the problem is resolved.
me too with same #368…..
no such file to delete………
same error here..
and same
Can you tell me about that hidden PHP in detail and which hosting platform you are using?
RESPOND QUICK lol
same Error here..
can you please tell me which php file to delete in detail or which hosting provider you are using.. help me out brother !
Respond ASAP !
Hi i tried to upload a photo but i’m getting this message !
(#324) Requires upload file
Hi Saran,
I followed all the steps mentioned above.
I am using localhost as my website.
I am a beginner and i am unable to implement it.
could you please provide me steps to implement this.
I have already created a fb page and created the 3 above files mentioned.
But still it is not executing.
Thanks and Regards,
Shavneet Singh
Hey, I was wondering if there is any way to post a photo that is already uploaded somewhere just using it’s link?
Is there anyway I can get this to post automatically to data from a MySQL database to the facebook wall via a cron job without having to login automatically?
Great script!
A question on images. I can get the image to upload and appear, but unlike the messages etc, the image actually appears on the admins wall and not the (Business) Page?
Is there any reason for this as I really need the image on the Page and not a users stream?
Thanks!
(#368) The action attempted has been deemed abusive or is otherwise disallowed
I am getting this error while posting
Great article. Very well presented and provided the instructions are correctly followed, this does EXACTLY what ‘it says on the tin’.
Thank you
Hi,
I am just curious to know whether it is possible to know the insights(likes, comments,views) of photos uploaded via this app to user walls.
The demo do not work !!!!
Hi,
any ideas how to post a youtube video so as when pressing on image/link it would not redirect, but would play instantly?
Your demo does not work why is that???
“Could not get your page details, make sure you have created one or you need to log in again! Click here to try again!” I AM logged in!
So i click the link and nothing happens ://
Thanks.