Posting to Facebook from website with Facebook Connect

This post is part of the Facebook Connect Tutorial and it will show how to add “post to wall” function to your community. Since every community is different, and since every community has different services we want to create a fbcpost.php file that can be connected to everything your users do. So we want to make a file that can be used for posting your users’ news on facebook, but also we want to re-use that file also for posting photos, forum threads and what ever your users can do.

Posting to users wall means posting objects like this on Facebook:


To do this we will change the normal stream of your codes from the red version to the blue version on the right of this flowchart (suppose you have a form that users use to post news):


Only 3 changes to your community:

  1. modify the form that post to add the chckbox visible only for facebook users
  2. change the page that receive data to handle the new checkbox, if posted
  3. add the fbcpost.php file that post to Facebook

STEP 1: modify your form that post data

So, suppose you have a form on your community where users logged in can post content (remember that we have already modified your community to handle Facebook users – see the turorial – because we need to know if user has a Facebook account).

If a user has a Facebook account connected (this means that you have the fb_userid field filled in the db as explained in the turorial), you can add a checkbox to the form, this checkbox tells something like: “check to post on your Facebook wall“.

STEP 2: handle the new checkbox

The page that receive data still keeps doing the same thing as before: save posted data, write to db, save picture, etc. etc., but if  the page has also received the checked checkbox that tells to post data to Facebook, then you have to create a new form with the items to be posted on the wall, so, create an HTML form and post it to the fbcpost.php page:

// ...
// before this do everything to handle normal post
// then, if checkbox checked output this html form:
if ($checkbox_is_checked) {
	<form id='postfb' method='post' action='/fbcpost.php'>
		<input type='hidden' name='t' value="<?=$title=>" />
		<input type='hidden' name='c' value="<?=$caption?>" />
		<input type='hidden' name='h' value="<?=$url_of_the_link?>" />
		<input type='hidden' name='d' value="<?=$description?>" />
		<input type='hidden' name='i' value="<?=$image_url?>" />
		<input type='hidden' name='al' value="<?=$action_link?>" />
		<input type='hidden' name='al' value="<?=$action_label?>" />
		<input type='hidden' name='callback' value="<?=$callback?>" />
	<!-- post the form automatically -->
	// when  you print this form your page change, so do not put any usefull code below
	// since this probably will not work as expected.

Those variables will be used by the fbcpost.php file to be putted here, on your Facebook’s wall:

The $callback variable is the url of the ending page of the flowchart, the page where you normally redirect user after saving posted data.

STEP 3: the fbcpost.php file

Here is the code that makes the job, there is something important that deals with Facebook permissions: since normally you can’t post to Facebook user’s wall without permission, this page has some javascript code that check for permission and if you have send the post, else it pops up the Facebook dialog box to ask the user for the missing permission.

There are different permissions: you can ask permission to send emails, to upload photos, to post on the wall and many more. Here we need the permission to post on the user’s wall, it’s called the “publish_stream” permission.

Read the code that is full of comments, and should explain by itself:

// this file includes FB_API_KEY and FB_SECRET constants and the ConnectDB function
// to connect to your mysql database.

// the php facebook api downloaded at step 3

if(!ConnectDB()) die;

$fb=new Facebook(FB_API_KEY,FB_SECRET);

// read the variables from the post, here
// you should add some check to avoid
// bad posts or attacks (at least strip tags
// and handle quoted strings).
$title = ($_POST['t']);			// title
$caption = ($_POST['c']);		// caption below the title, before the description
$url_of_the_link = ($_POST['h']);	// link of the url
$description = ($_POST['d']);		// some text that describe the object sent to facebook
$image_url = ($_POST['i']);		// image url (if exists)
$callback = ($_POST['callback']);	// callback url
$action_link = ($_POST['ah']);	// action link;
$action_label = ($_POST['al']);	// action label;

if(!$fb_user) {
	// If not a user on Facebook
	// redirect to the callback page
	// without posting anything.

<html xmlns="" xmlns:fb="">
	<script src="" type="text/javascript"></script>
<!-- on load do the job -->
<body onload="publish_with_permission('publish_stream');">
	I'm sending your stuff to yout Facebook wall.<br/>
	If it doesn't work you should give us the permission to publish streams on your wall.<br/>

<!-- do the job with javascript, and create the object to post through php vars -->

var action_links =  [{ 'text' : "<?=$action_label?>", 'href' : "<?=$action_link?>" }] ; 

var attachment = {'name' : "<?=$title?>", 
	'href' : "<?=$url_of_the_link?>", 
	'caption' : "<?=$caption?>", 
	'description' : "<?=$description?>"<?
		if($image_url) {
			echo ",'media' :[{'type' : 'image', 'src' : \"$image_url\", 'href' : \"$url_of_the_link\"}]";

function jscallback (post_id, exception) {
	// this javascript function is called
	// after the Facebook process and we use
	// it to go back to the correct page
	// where the post should end (the ending
	// page of the flowchart).
	if (post_id == null || post_id == undefined ) {
		// failed
	} else {
		// success

function publish_with_permission(permission) {
	// This function checks if user has permission, if not pops up the
	// Facebook dialog and ask for permission.
	// If permission is granted send without asking
	// anything, if permission is not granted pops up
	// and try to send again prompting for a comment.
	FB.ensureInit(function() {
			//check is user already granted for this permission or not
			function(result) {
				// prompt offline permission
				if (result == 0) {
					// show the facebook permission dialog
						if (!result) {
							// no permisson granted, pop up facebook dialog to post;
							FB.Connect.streamPublish('', attachment, action_links, null, "Post this:", jscallback);
						} else {
							// permission granted, post without facebook dialog
							FB.Connect.forceSessionRefresh(function() {
								FB.Connect.streamPublish('', attachment, action_links, null, "Post this:", jscallback,true);
					}, true, null);
				} else {
					// permission already granted, post suddenly
					// without facebook dialog
					FB.Connect.streamPublish('', attachment, action_links, null, "Post this:", jscallback,true);

<script type="text/javascript">  FB.init("<?=FB_API_KEY?>", "/xd_receiver.htm"); </script>

This file can be used to post everything on user wall, just define the variables to be posted in your pages where you want to post data.

Anything to say?

Comments with Facebook or below with WordPress

WordPress comments:

  1. Hi!, Thanks a lot for this script, and tutorials. I could cobble the previous scripts in no time, but i am having a tough time understanding this second thing i.e. this fbcpost.php. I dont see any form in fbcpost.php submitting to the final destination…… please help me with this confusion

  2. I think my question is how to modify the fbclogin.php, I understand that the auto submit form has to go into it, but it already contains forms that auto submit to the final destination.

  3. the fbcpost.php file receive a post from the page you’re modifying and send data to facebook with the API functions, not with a post.

  4. Ok, so the user will have to already logged in? i thought login and posting to wall will be simultaneous, I am trying to post some thing on the users wall, when he logs in, but i guess this script posts what the user posts on my website to his wall. am i getting it right ?

  5. Yes they have. This code lets you post to the users’ wall, but you need first to log in as described on the other post. First install the fbclogin.php and then fbcpost.php.

  6. Hello, I found this post while searching for help with JavaScript. I’ve recently switched browsers from Chrome to Microsoft Internet Explorer 5. Now I seem to have a problem with loading JavaScript. Every time I browse page that needs Javascript, my computer does not load and I get a “runtime error javascript.JSException: Unknown name”. I cannot seem to find out how to fix the problem. Any aid is very appreciated! Thanks

  7. Your post is smashing. There are some things that can be discussed here but don’t have the time right now. I’m bookmarking this page and leave this post to check again later and update my first comment (this one). By the way i found your blog post as i was searching for similar subjects in Google

  8. If you keep on submitting well written articles just like this then I am going to continue returning back to your web site. Wonderful information.

  9. Himm Interesting article and one which should be more widely known about in my view. Your levels of detail is good and the clarity of writing is excellent. I have bookmarked it for you making sure that others will be able to see what was have to say.

  10. Hi,

    I guess this example is using the old Facebook Rest API and not the new Graph API.
    Is that correct?


  11. Yes it’s the old API. It still works on my site, but I don’t know if you can use it now, for a new facebook application.

  12. For reasons unknown i’m ending up with a blank page after i attempt to post a comment,do you recognize reason why its encountering?i’m employing oprea web-browser.

  13. I’ve been browsing online more than 3 hours today, yet I never found any interesting article like yours. It’s pretty worth enough for me. In my view, if all web owners and bloggers made good content as you did, the web will be much more useful than ever before

  14. It is appropriate time to make some plans for the future and it’s time to be happy. I have read this post and if I could I want to suggest you some interesting things or suggestions. Perhaps you could write next articles referring to this article. I wish to read more things about it!

  15. Very high-quality write-up. I just bookmark your blog plus wants to be able to say that I have certainly enjoyed while reading through your articles. Thank you for sharing the knowledge with all.

Sorry, WordPress comments are closed on old posts.