+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

Leave a Reply to mishu Cancel reply

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