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:

post_example

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):

modified

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?>" />
	</form>
	<!-- post the form automatically -->
	<script>document.getElementById('postfb').submit();</script>
	<?
	// when  you print this form your page change, so do not put any usefull code below
	// since this probably will not work as expected.
	die;
}
?>

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

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.
include("settings-and-functions.php");

//
// the php facebook api downloaded at step 3
include("fb/php/facebook.php");

if(!ConnectDB()) die;

$fb=new Facebook(FB_API_KEY,FB_SECRET);
$fb_user=$fb->get_loggedin_user();

// 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.
	die("<script>document.location.href='$callback';</script>");
}

?>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:fb="http://www.facebook.com/2008/fbml">
<head>
	<script src="http://static.ak.connect.facebook.com/js/api_lib/v0.4/FeatureLoader.js.php" type="text/javascript"></script>
</head>
<!-- on load do the job -->
<body onload="publish_with_permission('publish_stream');">
<p>
	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/>
</p>

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

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
		document.location.href="<?=$callback?>";
	} else {
		// success
		document.location.href="<?=$callback?>";
	} 
}

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() {
		FB.Connect.requireSession(function(){
			//check is user already granted for this permission or not
			FB.Facebook.apiClient.users_hasAppPermission(permission,
			function(result) {
				// prompt offline permission
				if (result == 0) {
					// show the facebook permission dialog
					FB.Connect.showPermissionDialog(permission,
					function(result){
						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>
<script type="text/javascript">  FB.init("<?=FB_API_KEY?>", "/xd_receiver.htm"); </script>
</body>
</html>

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.

  1. Facebook Connect Tutorial, new version
  2. Facebook Connect Tutorial
  3. Updated version of the the Facebook Connect Tutorial
  4. PHP curl bot to update Facebook status
  5. Copying remote files on your server with PHP

36 comments

  1. sam

    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. sam

    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. admin

    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. sam

    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. admin

    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. Jeffrey Cade

    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. Rickie Gojcaj

    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. Perry Fisser

    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. qingrenjie gift

    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. Friedrich Zohmann

    Hi,

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

    thanks

  11. facebook

    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.

  12. Pingback: Facebook Connect how to PHP | Open source Tutorials News and how to's
  13. world wide Sports News

    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. Missouri city electrician

    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. Hard Porn Movies

    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.

  16. Pingback: Facebook Connect Tutorial เชื่อมต่อเวปเรากับ facebook ใน 8 นาที « สอนเขียนโปรแกรม
  17. Pingback: Facebook Connect Tutorial เชื่อมต่อเวปเรากับ facebook ใน 8 นาที « สอนเขียนโปรแกรม

Post a comment

You may use the following HTML:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>