Thursday, June 07, 2007

Writing a Facebook App

I've been writing a Facebook app. They offer a Java client library (as well as several other non-official ones for other languages) but I'm using the PHP one. I really like the library they include. It has been incredibly easy to use, even for a PHP hacker like me.

One of the best parts of their library is the FaceRestClient call_method function. Only problem is that it does not work with photo uploads. Of course that happened to be one of the things I wanted to do. It doesn't work because you need to set a multi-part mime header for a photo upload and format the binary data per that content-type. Obviously all this can be done by hand, but luckily I found something better: the photos lib. This makes it trivial to upload an image. Here's the code I wrote for it:

include_once 'facebookapi_php5_restlib.php';
include_once 'facebook_php5_photoslib.php';

// get your own api_key and secret!
$facebook = new FacebookPhotosRestClient($api_key, $secret);

// user logged in prior to uploading pic, so sesion key passed as param
$session_key = $_REQUEST['session_key'];
$facebook->session_key = $session_key;

$tmpLocation = $_FILES['uploadedfile']['tmp_name'];

if (is_uploaded_file($tmpLocation)){
$aid = $_REQUEST['album'];
$caption = $_REQUEST['caption'];
$res = $facebook->photos_upload($tmpLocation, $aid, $caption);
echo "Here is a link to your pic, make sure you approve it first:".$res['link'];
} else {
echo "Ye gods! Something went wrong!";


Jeremy said...

Great to see my photo library being put to use!

Let me know if you find any problems with it.

Good luck with your app!

Anonymous said...

good. Thanks.