Home >
Welcome to our new series that will cover the techniques necessary to create advanced Facebook applications that fully utilize the Flash, PHP and the Facebook API. This is the first article of the series. Please note that every article is not independent and in order to understand, let's say article 3, you must read article 1 and 2 etc.

As we all know life is much more colorful with friends, Facebook is the best example on the internet for this case. It's even more colorful when you can use the Facebook API to create applications on that platform. Using Flash, PHP and the FB API we can utilize ActionScript OOP features to make the applications perform better then with standard FBML. I'm not trying to say here that FBML is bad, no, this series will try to teach how to implement existing knowledge of Flash into the Facebook application platform. Take a quick look here at my app, which uses ActionScript 3.0, PHP and Google Maps. The problem with those technologies is that the knowledge is scattered through the Web and you need a lot of patience to assemble those pieces. Fortunately, you have me. I did a lot of hard work and I will share my experience for you.
I don't need to tell you a lot about Facebook applications. But there are more and more users who simply don't like Facebook applications because they don't really have a purpose and do not solve a real world problem. This is the issue that this series tries to address. The goal is to use ActionScript, PHP and the existing FB API to create truly useful applications that users will love and come back. That's not an easy task!
I will not talk a lot about the technologies as we want to get into the action as soon as possible. I admit that there might be better ways of to use Flash inside Facebook, but this approach proved to be successful in my previous projects, which had a few thousand users, so you want be wrong following this series.
Let's get our hands dirty!
So, let's examine all the tools we need to work on this:
1. First of all we need at least Flash CS3, you may use CS4. Because we use the core ActionScript 3.0 features there is no difference if we use CS3 or CS4.
What knowledge is required here?
1. A basic understanding of ActionScript, PHP and general OOP concepts.
So if you've never built a Facebook application before, read the mentioned tutorial and practice a bit. This series assumes that you are already familiar with the setup of Facebook apps.
In this article, we will create a simple application that will help you gain confidence and prepare you for more complex stuff that follows. Don't expect any kind of spectacular stuff here as this is intended to get you off the ground and will serve as a basis for future apps.
You should have a screen similar to this:
<?php
//////////////////////////////////////////////////////////////////////
//
// main.php
//
///////////////////////////////////////////////////////////////////////
//include facebook api etc.
require_once("pathToYourFacebookLibrary/facebook/client/facebook.php");
//create new facebook instance
$facebook = new Facebook(YOUR_KEY, YOUR_SECRET);
//prompt the user to login
$fb_user = $facebook->require_login();
//check if the user has added the app
if (!$facebook->api_client->users_isAppUser()) {
//if not, redirect him to add it
$facebook->redirect($facebook->get_add_url());
}
?>
<!-- flash file -->
<fb:swf swfsrc='http://www.yourServer.com/yourApp/main.swf' allowscriptaccess='always' bgcolor='#ffffff' wmode='transparent' flashvars='' width='500' height='400'/>
//include facebook api etc.
require_once("pathToYourFacebookLibrary/facebook/client/facebook.php");
//create new facebook instance
$facebook = new Facebook(YOUR_KEY, YOUR_SECRET);
//prompt the user to login
$fb_user = $facebook->require_login();
//select the profile image
$photoData = $facebook->api_client->users_getInfo($fb_user, 'pic_big');
Array(
[0] => Array(
[uid] => 1110516263
[pic_big] => http://profile.ak.facebook.com/v224/120/49/n1110516263_7773.jpg
)
)
$photoData[0]['pic_big'];
$photo = $photoData[0]['pic_big'];
<fb:swf swfsrc='http://www.yourServer.com/yourApp/main.swf?photo=<?= $photo ?>' allowscriptaccess='always' bgcolor='#ffffff' wmode='transparent' flashvars='' width='500' height='400'/>
...main.swf?photo=
<?= $photo ?>
...
<?php
//////////////////////////////////////////////////////////////////////
//
// main.php
//
///////////////////////////////////////////////////////////////////////
//include facebook api etc.
require_once("pathToYourFacebookLibrary/facebook/client/facebook.php");
//create new facebook instance
$facebook = new Facebook(YOUR_KEY, YOUR_SECRET);
//prompt the user to login
$fb_user = $facebook->require_login();
//check if the user has added the app
if (!$facebook->api_client->users_isAppUser()) {
//if not, redirect him to add it
$facebook->redirect($facebook->get_add_url());
}
//select the profile image
$photoData = $facebook->api_client->users_getInfo($fb_user, 'pic_big');
$photo = $photoData[0]['pic_big'];
?>
<!-- flash file -->
<fb:swf swfsrc='http://www.yourServer.com/yourApp/main.swf?photo=<?= $photo ?>' allowscriptaccess='always' bgcolor='#ffffff' wmode='transparent' flashvars='' width='500' height='400'/>
//retrieve the variable sent from php
var paramObj:Object = LoaderInfo(this.root.loaderInfo).parameters;
var photoSrc:String = String(paramObj["photo"]);
//display the image...
img_mc.source = photoSrc;
$friends = $facebook->api_client->friends_get();
Array
(
[0] => 2022256
[1] => 30811372
[2] => 61802896
[3] => 501579407
[4] => 501668263
[5] => 502578999
[6] => 503611040
[7] => 513106993
.
.
.
$friends = $facebook->api_client->friends_get();</div>
//calculate how many friends we have
$friendCount = count($friends);
//create a new array to store the 10 randomly selected friends
$selFriends = array();
//init the counter var
$i = 0;
//iterate 10 times
while($i < 10){
//pick a random friend from the list
$random = (rand() % $friendCount);
//add the friend to the selected friends
array_push($selFriends, $friends[$random]);
$i++;
}
//now simply get the profile images and statuses using the api method and the array
$profileImages = $facebook->api_client->users_getInfo($selFriends, 'pic_big');
$statuses = $facebook->api_client->users_getInfo($selFriends, 'status');
$i = 0;
$len = count($profileImages);
$queryStr = "?";
for($i = 0; $i < $len; $i++){
$img = $profileImages[$i]['pic_big'];
$status = urlencode($statuses[$i]['status']['message']);
//concat the strings
$queryStr .= ("image".($i + 1)."=".$img."&status".($i + 1)."=".$status."&");
}
?image1=http://profile.ak.facebook.com/v224/120/49/n1110516263_7773.jpg&status1=This is my status&image2
<fb:swf swfsrc='http://www.yourServer.com/yourApp/main.swf<?= $queryStr ?>' allowscriptaccess='always' bgcolor='#ffffff' wmode='transparent' flashvars='' width='500' height='400'/>
<?php
//include facebook api etc.
require_once("pathToYourFacebookLibrary/facebook/client/facebook.php");
//create new facebook instance
$facebook = new Facebook(YOUR_KEY, YOUR_SECRET);
//propmpt the user to login
$fb_user = $facebook->require_login();
//check if the user has added the app
if (!$facebook->api_client->users_isAppUser()) {
//if not, redirect him to add it
$facebook->redirect($facebook->get_add_url());
}
$friends = $facebook->api_client->friends_get();
//calculate how many friends we have
$friendCount = count($friends);
//create a new array to store the 10 randomly selected friends
$selFriends = array();
//init the counter var
$i = 0;
//iterate 10 times
while($i < 10){
//pick a random friend from the list
$random = (rand() % $friendCount);
//add the friend to the selected friends
array_push($selFriends, $friends[$random]);
$i++;
}
//now simply get the profile images and statuses using the api method and the array
$profileImages = $facebook->api_client->users_getInfo($selFriends, 'pic_big');
$statuses = $facebook->api_client->users_getInfo($selFriends, 'status');
$i = 0;
$len = count($profileImages);
$queryStr = "?";
for($i = 0; $i < $len; $i++){
$img = $profileImages[$i]['pic_big'];
$status = urlencode($statuses[$i]['status']['message']);
//concat the strings
$queryStr .= ("image".($i + 1)."=".$img."&status".($i + 1)."=".$status."&");
}
?>
<fb:swf swfsrc='http://www.yourServer.com/yourApp/main.swf<?= $queryStr ?>' allowscriptaccess='always' bgcolor='#ffffff' wmode='transparent' flashvars='' width='500' height='400'/>
function setImage(e:String):void{
img_mc.source = e;
}
function setStatus(e:String):void{
status_txt.text = e;
}
import flash.utils.Timer;
import flash.events.TimerEvent;
import fl.transitions.Tween;
import fl.transitions.easing.*;
import fl.transitions.TweenEvent;
//retrieve the variable sent from php
var paramObj:Object = LoaderInfo(this.root.loaderInfo).parameters;
var timer:Timer = new Timer(3000);
timer.addEventListener(TimerEvent.TIMER, switchUser);
timer.start();
function switchUser(e:TimerEvent){
var randNum:Number = Math.round(Math.random() * 6) + 1;
friend_mc.setImage(paramObj["image" + randNum]);
friend_mc.setStatus(paramObj["status" + randNum]);
var aTween:Tween = new Tween(friend_mc, "alpha", Strong.easeOut, 0, 1, 3, true);
}
Continue to Part 2, Overview of Embedding SWFs into Facebook Canvas
To view the entire series please visit http://www.insideria.com/series-facebook-dev.html




Facebook Application Development
Hi, where can I find the article 1,2 or 3?
Hi,
it will be published next week. :-)
Every week a new one will be published.
Regards,
Mirza
The whole series will be aggregated at http://insideria.com/series-facebook-dev.html. If you'd like to get these in a feed, you can subscribe to Mirza's feed: http://www.insideria.com/mirza-hatipovic/atom.xml
Dear Mirza,
I readed your tutorial because of the problem I have with Flash-PHP integration in Facebook application development. I think that following line of your code is wrong:
fb:swf swfsrc='http://www.yourServer.com/yourApp/main.swf' allowscriptaccess='always' bgcolor='#ffffff' wmode='transparent' flashvars='' width='500' height='400'
because facebook owerride allowscriptaccess always with "NEVER" value. I have problem with transfering variables from Flash to PHP, because actionscript addition to SEND or GETURL commands: "_self" "_top" and "_parrent" dont work if allowscriptaccess is set to NEVER. Only "_blank" work, but this command always open NEW WINDOW, which is not acceptable by my program.
Do You have some solution to this problem ?
How can you transfer variable from FLASH to PHP witouth opening a new window ?
Thanks for yor answer in advance.
Hi David,
I know about this issue...indeed the allowscriptaccess value is always set to never. In the later tutorials (article 3 and 5) there are methods explained how to transfer all kinds of php variables from to flash on the fb platform...so please be patient :-)
Svaka cast buraz, samo naprijed!!!
Pozdrav
Hi Mirza,
I'm follow this tutorial, but i have problems with Php conection to facebook. When i test the app, facebook send a error like this:
Parse error: syntax error, unexpected T_STRING, expecting '(' in /homepages/23/d245/htdocs/probes/main.php on line 20
I have installed the client library and i am testing with php 5 and php4client.
and i don't get the return values from facebook.
Can you help me, plese
Thank you.
Hi,
About my last comment:
The message error from facebook when i use the php 5 client library is this:
Parse error: syntax error, unexpected T_STRING, expecting T_OLD_FUNCTION or T_FUNCTION or T_VAR or '}' in /homepages/23/d245/htdocs/probes/php/facebook.php on line 38
Thank you
Hey thanks for the tutorial, its great!
Anyway i follow some minor rev (code/tag) on Facebook, example $fb_user is changed to $user. And some other minor rev.
But thats okay, i love your tutorial!! Keep it update, im your fan! =D
Please send me a code
Thanks for sharing
You welcome :-)
I have some problem when testing. I put everything but when I test, instead of getting in the first part the blank page i get these part of the php document displayed: "require_login(); //check if the user has added the app if (!$facebook->api_client->users_isAppUser()) { //if not, redirect him to add it $facebook->redirect($facebook->get_add_url()); }". What could it be?
Gompa,
it seems like you facebook pages are not saved as php :-) they are parsed as normal html documents...check your file extensions, also check if your server supports php
Your application fails in PHP5. I get an error message saying that says
Cannot use string offset as an array in /home/content/w/o/r/worldshaker/html/facebook/fbflash/index.php on line 62.
Which is a PHP5 error from what I have found. I have been looking at your code but I am not a PHP expert. If you have a fix for this please post it for people using PHP5 and up.
Thanks,
Your application fails in PHP5. I get an error message saying that says
Cannot use string offset as an array in /home/content/w/o/r/worldshaker/html/facebook/fbflash/index.php on line 62.
Which is a PHP5 error from what I have found. I have been looking at your code but I am not a PHP expert. If you have a fix for this please post it for people using PHP5 and up.
The error is in here.
$img = $profileImages[$i]['pic_big'];
$status = urlencode($statuses[$i]['status']['message']);
//concat the strings
$queryStr .= ("image".($i + 1)."=".$img."&status".($i + 1)."=".$status."&");
line 62 is the $img = $profileImages[$i]['pic_big']; line
and
$status = urlencode($statuses[$i]['status']['message']);
will produce the error also.
Thanks,
Your application fails in PHP5. I get an error message saying that says
Cannot use string offset as an array in /home/content/w/o/r/worldshaker/html/facebook/fbflash/index.php on line 62.
Which is a PHP5 error from what I have found. I have been looking at your code but I am not a PHP expert. If you have a fix for this please post it for people using PHP5 and up.
The error is in here.
$img = $profileImages[$i]['pic_big'];
$status = urlencode($statuses[$i]['status']['message']);
//concat the strings
$queryStr .= ("image".($i + 1)."=".$img."&status".($i + 1)."=".$status."&");
line 62 is the $img = $profileImages[$i]['pic_big']; line
and
$status = urlencode($statuses[$i]['status']['message']);
will produce the error also.
Thanks,
Hi,
Nice article..
I have one doubt. From my site, I am accepting facebook login. Once the user login to the site, I need to display my friends email address in one select box. How can I do it ?
Regards
Binoy
Thanks , New to the blog & api – great resource!
I’ve gotten through day one of getting things to work as a Flex desktop-mode app in debug, but I’m having trouble getting it to actually launch from Facebook.
Thank you for the great tutorial! Looking forward to diving into the rest of the series.
I'm not sure if you cover this in next tutorials, but in this case a better approach would be to use FQL. This way you will only make one API call instead of several, simplify things on the PHP side, also take care of filtering out users with no status message.
CODE:
---------------------------------------------------------------------
// Select 10 random friends whose status is not empty.
$fql = 'SELECT pic_big, status.message FROM user
WHERE status.message != ""
AND uid IN (SELECT uid2 FROM friend WHERE uid1 = ' . $user->id . ')
ORDER BY rand() LIMIT 10';
$result = $facebook->api_client->fql_query($fql);
// Create the query string.
$query = '?';
foreach ($result as $i => $friend_data) {
$query .= 'image' . ($i + 1) . '=' . $friend_data['pic_big'] . '&status' . ($i + 1) . '=' . urlencode($friend_data['status']['message']) . '&';
}
Thanks for this tutorial. I have managed to load my 'main.swf' from the first tutorial but cant access the thumbnail from my UIloader (I have named it img_mc in the property inspector).
I note that the UIcopnenet is no longer referred to as 'fl.containers.UIloader' but now simply 'UIloader' in Flash CS4. Would this impact the tutorial at all, or perhaps be the reason that I'm not loading the tumbnail successfully?
Thanks again, I raelly hope that you can help.
:)
Sorry to spam the page!! And thanks agan for all your help to such a beginner.
When you incluide the facebook api in main.php, is this supposed to be modified with a url to the facebook.php file?
"pathToYourFacebookLibrary/facebook/client/facebook.php"
Or does this stay the same?
I'm honestly not sure why the flash file is loading, but can't access the thumbnail!! lol
Thanks again
Badger
thanx....but i have problem...i want that facebook script which send direct message to facebook account..please help me..waiting for reply today.
Great work on the Hair Cut Stylist App!! Awesome, and looking forward to the complete series that you have started on Youtube.
I have had 2 apps approved since I last posted, so I'm now up to speed on the Facebook API, to a reasonable level (been coding for years too).
I'm still having difficulty passing flashvars to CS4. I assume that you dont need the Facebook libraries or rather the SWC for this tutorial to work? The swf still loads, but with no image.
Hope you can help at all, and that all is going well,
Best
Barnaby
I just got this to work after a month of practising/working hard on Facebook app development. Thanks so much for all your help my friend. I will forward the results after I have a chance to move onto your next tutorials!! Without this, I wouldn't have been able to link Flash to Facebook, I thank you again.
:D
Best
Badger
I added code to ensure that it doesn't display the same image twice consecutively:
function switchUser(e:TimerEvent)
{
var oldrandNum:Number = randNum;
var randNum:Number = Math.round(Math.random() * 6) + 1;
// while oldrandNum is equal to randNum, pick another until unique
while(oldrandNum = randNum)
{
var randNum:Number = Math.round(Math.random() * 6) + 1;
}
Works fine, I also have set the alpha to 70% and put an image behind. Looks very 'Flash'!!
@Anastasia:
I like the idea of using fql, but there are syntax errors in your code. The following should work better for fql:
$friends = $facebook->api_client->friends_get();
// Select 10 random friends whose status is not empty.
$fql = 'SELECT first_name,last_name,pic_square, status.message FROM user WHERE status.message != ""
AND uid IN (SELECT uid2 FROM friend WHERE uid1 = ' . $fb_user . ') ORDER BY rand() LIMIT 20';
$result = $facebook->api_client->fql_query($fql);
echo"
result: " . $result . "
";
// Create the query string.
$query = '?';
for($i=0; $i {
$query .=
("image".($i + 1)."=".
$result[$i]['pic_square'].
"&status".($i + 1)."=".
urlencode($result[$i]['status']['message']).
"&name".($i + 1)."=".
urlencode($result[$i]['first_name']." ".$result[$i]['last_name'])."&");
}
echo"
QUERY STRING: " . $query . "
";
Hi,
I am unable to pass the variable containing the url to the image to the flash app.
My flash app works fine when invoked directly with the image url as argument:
example: http://my.hostserver.com/flashdemo/lesson2.swf?photo=http://www.flash-mx.com/images/image2.jpg
My flash also loads fine in facebook. But the image is not loading. The PHP snippet is below:
fb:swf swfsrc='http://my.hostserver.com/flashdemosrb/lesson2.swf?photo=http://www.flash-mx.com/images/image1.jpg' allowscriptaccess='always' bgcolor='#ffffff' wmode='transparent' flashvars='' width='500' height='400'/
I also tried the below code without success:
fb:swf swfsrc='http://my.hostserver.com/flashdemosrb/lesson2.swf?photo=' allowscriptaccess='always' bgcolor='#ffffff' wmode='transparent' flashvars='' width='500' height='400'/
my $photo variable has the correct value for image url.
Any ideas on what may be going wrong here?
Thanks, srb.
I didn't find: facebook/client/facebook.php
and i got the API class from:
http://code.google.com/p/facebook-actionscript-api/
Do i have the right classes?
Thanks for this great tutorial.
UILoader does load image indeed, but loading image via urlRequest and Loader does not. Is there a known issue about this?
WOW! Great post man I will see what i can come up with
Thanks
http://www.facebookloginhut.com/
Hi,
followed the tutorial up to the bit when I am displaying the first image but I got this message: The URL http://www.............returned HTTP code 200 and no data. Does anyone know why?
Anonymous...try putting the API key & secret key in single quotes. That seemed to work for my but now my page is just blank. It's not loading the .swf file.