+40 745 232 788

Online Solutions Development Blog   |  

RSS

Post to facebook wall using php

Getting the needed permissions and writing on an user’s facebook wall seems something complicated, but once you get some basic things you will be able to develop applications that send updates to facebook accounts.

In order to be able to do this the account owner must give you access. If you think that by knowing the username and password you can do this you are wrong. You need to create a facebook application that the user agrees to use.

Create facebook application

First thing: create the facebook application. Go to http://www.facebook.com/developers/createapp.php

If this is the first time you are here you will need to allow the built in facebook app called “Developer” to access your account.

After completing the first basic steps (choosing a name for your application, entering captcha) you will get to the edit application details page.

Most of the fields will be very easy to fill in. You will need to be sure you enter the application site url and domain in the “web site” tab (this is just a page that shows details about your app) and the most important one: the canvas url. This address will need to point to the script that will save the details you need. So let’s say it will be something like http://localhost/fbapp/fb_users.php? (don’t forget the question mark).

Facebook Enter Canvas URL

Facebook Enter Canvas URL

After you save the application details you should see on the summary page the application id, api key and secret (some random codes like NEH3UVX38VPU). You will need them.

Ask for permissions

Now let’s get to the point.

You will need to download the facebook php sdk, located here and save it in your application directory.

Create a config file where you will save these values and create a database connection.

So a sample would look like this:

<?php
define('MYSQL_HOST',     'your_db_host');
define('MYSQL_USER',     'your_db_user');
define('MYSQL_PASSWORD', 'your_db_password');
define('MYSQL_DB',       'your_db_name');
define('TABLE_PREFIX',   'your_table_prefix');

try
{
$dbh = new PDO('mysql:host='.MYSQL_HOST.';dbname='.MYSQL_DB, MYSQL_USER, MYSQL_PASSWORD);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
	$dbh->setAttribute(PDO::ATTR_PERSISTENT, true);
	$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
	$dbh->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, true);
	$dbh->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, 1);
}
catch (PDOException $e)
{
	print "Error!: " . $e->getMessage();
	die;
}
define('FB_APIKEY', 'YOUR_FACEBOOK_APPLICATION_API_KEY');
define('FB_SECRET', 'YOUR_FACEBOOK_APPLICATION_SECRET');
require_once('facebook-platform/php/facebook.php');
?>

Save authentication token

Now we will need to create a simple script (called get_fb_approval.php) that redirects the user to the page where he will allow your application to access your account.

This example can be used for a multi-user application so let’s say you will ask for the facebook username in a previous step and now you will try to get the approval for that account. Just to keep this example simple we will consider that we will receive the facebook username in get (so we will test the script like this http://localhost/fbapp/get_fb_approval.php?user=_YOUR_FB_USERNAME_ )

This script will look like this:

<?php
require_once('config.php');
$facebook = new Facebook(FB_APIKEY, FB_SECRET);     // request permissions to write on the user's wall, even when he is online.
$loginUrl = $facebook->get_login_url('YOUR_CANVAS_URL_HERE?user=' . @$_GET['user'], 1, 'publish_stream,offline_access');
    header('Location: ' . urldecode($loginUrl));
    die;
?>

Notice that on the 3rd line you have YOUR_CANVAS_URL_HERE. Replace this with the canvas url you provided when you created the facebook app (something like http://localhost/fbapp/fb_users.php).

This way you will tell facebook to send you the data you need to this url and also the username that you sent (so you would know how to connect the users you have with the tokens you receive)

What we need now is the script placed at the canvas url.

You also need a table with this structure:

CREATE TABLE IF NOT EXISTS `fb_users` (
  `fb_user_id` int(10) NOT NULL auto_increment,
  `fb_user_username` varchar(30) NOT NULL,
  `fb_user_uid` varchar(20) NOT NULL,
  `fb_user_auth_token` varchar(100) NOT NULL,
  PRIMARY KEY  (`fb_user_id`)
);

(don’t forget about your table prefix)

This script will look like this:

<?php
require_once('config.php');
if (isset($_GET['session']) && isset($_GET['user'])) // you received the data you need
{
 		// $session = json_decode($_GET['session'], true, 512, JSON_BIGINT_AS_STRING); // this will work after php 5.3
 		// this way it will work for older php versions
 		$session = trim($_GET['session'], '{}');
 		$parts = explode(',', $session);
 		$auth_token = '';
 		foreach ($parts as $key=>$value) // extract the needed values from this array
		{
			$tmp = explode(':', $value);
			$var_name = trim($tmp[0], '"');
			$var_val = trim($tmp[1], '"');
			if ('secret' == $var_name)
			{
				$auth_token = $var_val;
			}
                        if ('uid' == $var_name)
                       {
                             $uid = $var_val;
                       }
		}
		$user = filter_var($_GET['user'], FILTER_SANITIZE_STRING);
                $auth_token = filter_var($auth_token, FILTER_SANITIZE_STRING);
                $uid = filter_var($uid, FILTER_SANITIZE_STRING);
		$query = '
					DELETE FROM
						'.TABLE_PREFIX.'fb_users
					WHERE
						fb_user_username = :username
		'; // delete old (maybe deprecated) user info
		$stmt = $dbh->prepare($query);
		try
		{
			$stmt->bindParam(':username', $user);
			$stmt->execute();
		}
		catch(PDOException $e)
		{
			//debug your query
		}
        // save the new info
        $query = '
                    INSERT INTO
                        '.TABLE_PREFIX.'fb_users
                    SET
                        fb_user_username = :fb_user_username,
                        fb_user_uid = :fb_user_uid,
                        fb_user_auth_token = :fb_user_auth_token
        ';
        $stmt = $dbh->prepare($query);
		try
		{
			$stmt->bindParam(':fb_user_username', $user);
			$stmt->bindParam(':fb_user_auth_token', $uid);
			$stmt->bindParam(':fb_user_auth_token', $auth_token);
			$stmt->execute();
		}
		catch(PDOException $e)
		{
                      //debug your query
		}
	}
//do what you want after you save the user info

Now you saved the most important thing you need: the authentication token.

Post new status

Everything is almost done. Now how will we use this things?

We will write a function that posts a message to someone’s wall so you will be able to use it the way you want

function send_to_facebook($username, $message)
{
        // don't forget about the database connection and to be user you included the facebook sdk
	global $dbh;
	require_once('facebook-platform/php/facebook.php' );
	$facebook = new Facebook(FB_APIKEY, FB_SECRET);
	$query = '
				SELECT
					*
                                FROM
					'.TABLE_PREFIX.'fb_users
				WHERE
					fb_user_username = :fb_user_username
                               ORDER BY
                                        fb_user_id DESC
                               LIMIT 1
	';
	$stmt = $dbh->prepare($query);
	try
	{
		$stmt->bindParam(':fb_user_username', $username);
		$stmt->execute();
	}
	catch(PDOException $e)
	{
              //debug your query here
	}
	$info = $stmt->fetch(PDO::FETCH_ASSOC);
	if (empty($info))
	{
		return false;
	}
	$facebook->api_client->session_key = $facebook->do_get_session($info['fb_user_auth_token']);
    try
    {
        $facebook->api_client->users_setStatus($message, $info['fb_user_uid']);
    }
    catch(Exception $e)
    {
        return false;
    }
	return true;
}

That’s all.

If you need to test this a number of times you will get the approval request page only the first time. In order to see it again you must remove your application from the list of apps you approved. You can do this here.

So now you know how to: ask the user for permission to write on his wall, save a facebook authentication token and most important: how to post on his wall.

If you have any questions, please feel free to add a comment to this post.

Edit:

As harry suggested, you can find an archive with all the needed source code to post on facebook wall here

You will find a file called README.txt inside the archive that tells what you need to do so that this script would work.

The code inside the archive is a bit different since it is a full working example, not just bits.
Thank you for the suggestion and I hope this sample will help you.

If you liked this post
you can buy me a beer

10 Responses to Post to facebook wall using php

  1. hello,
    i’m new at fb connect things, could make it like a simple script (with download link)?

  2. sure, thank you for the suggestion. I will add as soon as possible an archive with the php scripts used.

  3. thanks for the file mishu (:
    love your work!

  4. Bravo pt tutorial. Foarte util 🙂

  5. mishu … It is possible to allow users to post in their wall or to give the option to post in a my wall. The idea in my case is to provide some co-authors in a blog to post on our blog facebook page (one that we all share and maintain) or gyve the option to post in their on personal wall (their own facebook page).

    Any suggestion or ideas will be appreciated.
    Thanks and sorry for my english

    • Hello, Daniel.

      I never did something similar to what you are asking, I don’t know if there are any limitations to this. In the current example we use an authentication token that is saved in the session. Maybe you should try saving it in the database and see if you can switch two different tokens. From that point everything is an application design matter.

      If anyone else that reads this post has an idea you are all invited to share it with us 🙂

  6. First of all i would like to thank you so much for all of these great things you did.

    When i downloaded your zip file and changed all needed codes in config.php file and created my SQL database as required, then when i go to my domain and input my email address and press Go, so it’s just redirecting me to facebook homepage.

    I don’t know what is wrong with my code, knowing that i did the changes as follows:

    Config.php
    i changed ‘CANVAS_URL’ to “http://sayhappybd.tk/fb_users.php?” and it’s the same URL as my facebook settings.

    • Hello,
      The Facebook api and applications settings were changed since the time this post was written (more than 2 years ago) and some things might have changed. From what I know now you are required to provide a secure canvas url also for an application to work. Also you should check if the facebook platform that is part of this example is the latest version (I am guessing it’s not).

  7. Hey i just downloaded your code package, and tried to run it, for my app which generally post a blog into the Facebook wall. but the code is int working properly, can you help me out here. I’m a novice when it comes to Facebook development.
    The problem —>
    Whenever i give my email id, the page redirects me to the loin page of Facebook, but after that it simply takes me to my home page, and it doesn’t ask me for my new status. Can you explain why?
    Rather it says—> “Now you are done. Go back where you hosted this script and enter the username again.”

    • Hello,
      From what I see the problem you are reporting is very similar to the one described by amr above. As I said, this blog post is a bit old (more than two years) and there might be changes in the facebook api. I will investigate the problem and let you know if I find anything.
      There’s a big chance that the methods used here are no longer working after some updates in the facebook api. You can see in our recent post that describes a php quiz facebook app that the method used there to upload an image with a message is very different and changing statuses might be very similar now.

Add a Comment

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

Also, if you want to display source code you can enclose it between [html] and [/html], [js] and [/js], [php] and [/php] etc