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…

Gennaio 17, 2010

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.

Author

PHP expert. Wordpress plugin and theme developer. Father, Maker, Arduino and ESP8266 enthusiast.

Comments on “Posting to Facebook from website with Facebook Connect”

36 thoughts

  1. sam ha detto:

    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 ha detto:

    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 ha detto:

    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 ha detto:

    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 ha detto:

    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. Leoma Liaw ha detto:

    I have solved many of the issues I have had previously, just by coming to, I would highly recommend it for anyone in a similar position.

  7. Jeffrey Cade ha detto:

    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

  8. Nobility Title ha detto:

    Thanks for writing such a thought-provoking post. Let’s keep the comments relevant.

  9. Rickie Gojcaj ha detto:

    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

  10. Norberto Dodich ha detto:

    Nice work buddy! Stumbled for sure!

  11. Sterling Jewelry ha detto:

    Hi! Thanks for the excellent info. I will be back to see another post!

  12. Perry Fisser ha detto:

    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.

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

  14. qingrenjie gift ha detto:

    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.

  15. Theola Wilmont ha detto:

    Hey there, quite a good writeup. I’ve subscribed to the RSS feed in case I receive a reply from anyone. :p

  16. zune.net/setup ha detto:

    Thank you for conveying this website internet, my life time is more efficient today. :).

  17. OpenGraphy ha detto:

    thank you for info too, I had tried it but it doesn’t work that well… we found a trick and adapted it for our apps

  18. Friedrich Zohmann ha detto:

    Hi,

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

    thanks

  19. Giulio Pons ha detto:

    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.

  20. Good content, keep us posting, you are good writer.

  21. facebook ha detto:

    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.

  22. newB ha detto:

    Sir, I admit your skill, but why you bother with that shit site?

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

  24. 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!

  25. Hard Porn Movies ha detto:

    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.

  26. server ebook ha detto:

    Hello, your weblog does not show correctly on the ipad2. Could you fix this?

  27. Daniel ha detto:

    Please i do not understand, u mind sending me the full script so i can download it, my mail is evameet@gmail.com

  28. google plus 1 ha detto:

    Merely looking at your current Website, how long have you had it? I enjoy the design

  29. jack ha detto:

    thanks for you minibot
    it is very userful.

  30. Good article, Can I translate it into Russian and write in my blog (with link to you)?

  31. Pardeep ha detto:

    thank you for info too…..

  32. Giulio Pons ha detto:

    Yes you can. Add a link to my site from your!

Comments are closed

Recommended

Social buttons: the fastest way for WordPress, without plugins

NOTE: the code in this post is written for WordPress but you can easily translate it in any language. You’re here…

Settembre 15, 2015

VK Social metrics, Top Stories plugin now with support for Vkontakte

VK SOCIAL METRICS VK.COM, also known as Vkontakte, is an important russian social network, which has over 270 million users.…

Novembre 19, 2014

Updated version of the the Facebook Connect Tutorial

I’ve written un updated version of the Facebook Connect Tutorial, you can find it in the top menu of Barattalo.it.…

Ottobre 10, 2012

How to read facebook likes count from PHP

When you add facebook like button to your site, probably, you also want to save the number of likes of…

Ottobre 8, 2012

New Facebook Invite all friends hack

So, you want to invote all your friends but the old hack doesn’t work anymore? With the last facebook friends…

Settembre 14, 2011

PHP to post on a Facebook page

Hi, I’ve modified the Mini Bot Class, I’ve fixed the Facebook status update and I’ve implemented the function to post…

Luglio 28, 2010