NOTE: This post was written using Facebook’s PHP SDK version 2.1.2. Since this post was made, the PHP SDK has changed and some of the process that are explained below may have changed as well. At some point I’ll have to revisit this post and update it but at this time just keep in mind of the above.
As promised, here is a post (similar to my Twitter API post) on using the Facebook API. There are many reason why one would want to access the Facebook API – maybe to create a mobile app that lets you post photos to your Facebook albums, or maybe you just want to show your last few Facebook status updates on your blog; what ever the reason may be, Facebooks Graph API mixed in with their PHP SDK makes it really easy to accomplish this.
Objectives
- Setup our environment
- Register an app on Facebook
- Understand the authentication process and extended parameters
- Understand Graph API
- Retrieve our latest status updates
- Add a new status update
- Retrieve our photos from our albums
- Add a new photo
Setup our Environment
You have two options here, you can access my github and download this project with all required files and library or you can follow this tutorial step by step – it’s really up to you. If you want to download all the files ahead of time, you can get them at this github repo. If you are going step by step, first create a folder (I’m calling mine facebook) in your server where you want this site, next create a folder named library in the root of this site, and finally add the following two files facebook.php and fb_ca_chain_bundle.crt in the library folder that you can get from the Facebook PHP SDK repo at: https://github.com/facebook/php-sdk/tree/master/src/.
Register an App on Facebook
I’m making the assumption you already have a facebook account and if you don’t, first create one. To create an app on Facebook, you first need to confirm your account by giving Facebook a phone number where they can send you a code. This may be a new process since I don’t remember having to do this a few months ago. Go to http://developers.facebook.com/setup and if your account is not verified, you’ll be prompted to add the information mentioned above. After verifying your accout, you’ll be taken to the ‘Create an Application’ page.

This is what the page should look like
Simply give your site a name and type in your site’s url and click create app. In my case I’m calling my app ‘Blog Test’ and my site would be ‘http://www.joeyrivera.com/’. Next you will be prompted to type in a captcha and continue. Now you are done setting up your app, you see a screen like the following with your app id and app secret:

Here is your app info
Authenticating and Extended Parameters
Facebook uses OAuth for authenticating involving tokens being send back and forth but we don’t have to concern ourselves with the details – the Facebook PHP SDK does it all for us. It makes sure to send all the required information in the proper format so Facebook gets what it needs and sends us back what we need. You can read more about authenticating with Facebook at their site and you can also read my Twitter API post that discusses the OAuth in a little more detail if you are interested. The SDK also takes care of handling all API calls for us so we only have to give it the resource we are trying to access, let it know if we want to do a get or post, and finally give it all the parameters required for the call.
Extended Parameters is an interesting way of restricting access to an app (I’m using the term app to describe what we are building here) through the API. Unless a user allows access to certain parts of their account, an app will not be able to modify nor read parts of the account even if they are authenticated. Extended Parameters need to be explicitly assigned at the point of authenticating. When the user is taken to Facebook and asked to allow access to their account, the user is also presented with all the various parts of their account this app wants to interact with. Here is an example of what the user will see when trying to authenticate with our app:
The first one in the screen shot is the default requested permission to access all the users basic information. The other three we need to accomplish our goals set including: read and post status updates as well as view and post photos. Here you can see a complete list of all the available extended permissions. If you access that link, you’ll see there are a lot of permissions. I recommend taking some time reading through their descriptions to get a better understanding of the kinds of things you can do with the API. There have been times where I’ve tried to do something with an app and the Facebook Graph API without success only to find out I hadn’t requested a required permission for that to work.
Time for code, what we are about to do is to create an array with our app id and app secret to feed to the Facebook class when we instantiate it. Next, we are going to check to see if we are authenticated and if not, redirect us to the Facebook authenticate page passing it the extended parameters we want access to. Below is the code for the config.php file. Download form my repository or create the file below on the root of your site:
config.php
$app_id = "yourappid";
$app_secret = "yourappsecret";
$facebook = new Facebook(array(
‘appId’ => $app_id,
‘secret’ => $app_secret,
‘cookie’ => true
));
if(is_null($facebook->getUser()))
{
header("Location:{$facebook->getLoginUrl(array(‘req_perms’ => ‘user_status,publish_stream,user_photos’))}");
exit;
}
Make sure to update the app_id and app_secret variables with the information you received from Facebook after registering your app. Let me give you a quick explanation of the code. First we include the facebook.php file that we downloaded from the Facebook PHP SDK github repository. Then we instantiate a facebook instance passing it the app id, app secret, and tell it to use cookies to store the session/token information after authenticating. Next we call getUser() to see if we are already authenticated – null means we are not, else we receive the users id. If we are not authenticated, we redirect the user to Facebook to authenticate. The url is provided to us from the getLoginUrl method. We are sending that method an array with a key req_perms (required permissions) and the value is a comma delimited list of all the extended permissions we want access to. Again, a complete list of all permissions can be found at Facebooks docs.
Go ahead and try to access this page in your browser. You should be immediately redirected to Facebook. If you are not already logged in with your Facebook account, you’ll first be asked to log in with the user which you want your app to access. Next you’ll see the ‘Request for Permission’ page, click allow and you’ll be taken back to the config.php page on your server. This process takes you back to the page which initiated the authentication which was the config.php page. We have now successfully authenticated with Facebook.
In testing your app, you may decide you need more or less extended permissions. While you are authenticated with Facebook and have your token stored in a cookie, you won’t be able to re-authenticate using this code since you’ll be getting a User object back so you have a few options: You can close your browser, clear cookies, and authenticate again after modifying your code; You can force another echo or header redirect to the getLoginUrl() again with the new parameters; or you can log into your Facebook account (the user you authenticated), click on account on the top right, privacy settings, and in the bottom left you’ll see application and websites, click on edit your settings. Under applications you use, you should see your app listed, click on edit settings. Finally click on the ‘x’ delete button to delete your app from the list. This will now remove your app from this users app list and won’t allow the app to access this account until the user authenticates again.
Graph API
This was confusing to me at first, specially since I keep rushing my project instead of taking my time to carefully look and read over the documents to truly understand what’s going on. Here is the Facebook Graph API overview if you would like to read that first but I’ll try to summarize it here. Graph API allows you to call various resources all of which will be returned to you as JSON objects. You’ll have to spend some time at the Graph API References page to understand the different objects available, parameters they have, and what the required extended permissions are to access them. I’ll try to explain connections in a sec.
Lets talk about the User object first. If you look at the reference page for user, you’ll see that to call the user object (the user who is authenticated by the app) you would call the graph api url with a ‘/me’ at the end. If the call is made successfully, you’ll receive a JSON object with all the possible properties defined in the reference page (if they are set). Here is a quick example.
user.php
If you run this code you get something like this:

This is my user object and properties.
Once you have the object, you can access it’s properties or do what you need with it. Now I’ll try to explain connections. If you look at the user reference page again and scroll down, you’ll see a connections section. These are the objects you can get that belong to this user. To access those objects you would call the url /me/object you want. For example, if you want to get this users albums, you would call /me/albums and this would return an array of album objects but remember to meet the required permission. For your app to access /me/albums, you need the user_photos extended permission (which we set in our config.php file).
So a connection is just a bridge between one object an another. Another example would be lets say we do as we did above and get all the users albums. Now we want to see all the photos inside each album. If you look at the album object, you’ll notice that under connections is photos which returns an array of photo objects. That is what we would call to get all the photos in that album for each album and you’ll see the code to do just this later on.
Get Status Posts
Create the following page and I’ll explain the code below.
status.php
// show statuses
$statuses = $facebook->api(‘/me/statuses’);
foreach($statuses[‘data’] as $status)
{
echo $status["message"], "<br />";
}
First include the config.php file we created earlier (you’ll include this in all the other pages as well). The api method is what we’ll be using every time we need to call a resource and it can take in three parameters: the resource, get/post (defaults to get), and params (if any). In this case we want to call the statuses connection in the user object which returns and array of status messages. After receiving the messages, we loop through each and echo them out. If you want to see all the properties of each status, just do a var_dump on each status. That’s it, now the next example.
Add New Status
Here we are doing something a bit different, we are publishing to Facebook and for more info you can look at the Facebook Graph API Overview in the publishing section. We want to create a new post so lets look at the reference guide for information on post and its properties. Scroll down to the publishing section and notice we need the publish_stream extended property and you can see all the different properties that this object supports. I’m personally a bit confused on what is considered a required property and what it not, is seems nothing is required but for this example we want to submit a post with a message.
status_add.php
// add a status message
$status = $facebook->api(‘/me/feed’, ‘POST’, array(‘message’ => ‘This post came from my app.’));
var_dump($status);
This is all the code required to make a post! It’s that easy. We call the api method, tell it we want to call the /me/feed connection, set method to post, and finally pass an array with the properties we want to set – in this case just the message property. If you wanted to set other properties, you would have set them in that array such as ‘link’ => ‘http://link.to.something’, etc. If the call is successfully, you’ll receive an id back which is the id for the new post you just created. Run this code and if all goes well, you should be able to go check our the users Facebook wall and see this latest post. I don’t think you can post the same message twice (unless I’m confusing Facebook with Twitter) so if you try it twice and it doesn’t work, that might be why.
View Photos From Albums
In this example, we want to get all the different albums for our user. Then we need to loop through each album and make a second call that will return all the photos for each album.
photos.php
// get albums
$albums = $facebook->api(‘/me/albums’);
foreach($albums[‘data’] as $album)
{
// get all photos for album
$photos = $facebook->api("/{$album['id']}/photos");
foreach($photos[‘data’] as $photo)
{
echo "<img src=’{$photo['source']}’ />", "<br />";
}
}
Here we call the albums connection on user to get all the album objects. We loop through each and for each album get the album id to then call the photo connection on the album object. If this sounds confusing just let me know and I’ll try to explain this further. When I think of connections I think of joins in a db. It’s like saying I want to join the albums table for the user in the user table therefor retrieving all rows in ablum for a specific user.
Add Photo
In the interest of time and complexity, I’m just going to add a photo without specifying an album. By doing this, Facebook will automatically create a new album to add this photo to. Just know that you can specify an album to add photos directly too if needed.
photos_add.php
$img = realpath("C:\\path\\to\\file.jpg");
// allow uploads
$facebook->setFileUploadSupport("http://" . $_SERVER[‘SERVER_NAME’]);
// add a status message
$photo = $facebook->api(‘/me/photos’, ‘POST’,
array(
‘source’ => ‘@’ . $img,
‘message’ => ‘This photo came from my app.’
)
);
var_dump($photo);
I choose this example for people that want to understand how to post a file through a service like this. First lets start at the top. We need to specify the path to the image we want to upload so change that path to where you file resides. Usually this would be the tmp path for a photo just uploaded to your server via $_FILE. Next we need to tell facebook to allow uploading of a file. I didn’t investigate that method much other then the comments said to specify the server so I use SERVER_NAME to signify this server. Next we make the call. We are calling /me/photos since that’s what is specified in the photos reference page under publishing. We are passing two parameters, message is the text that will show up with the image and source is the image we want to upload. Notice there is an @ before the path to the image. This is because we want to post the contents of the file and not pass a string to where the file is. Run this code and if all worked well, you’ll see this image and an new album in your users Facebook page.
Conclusion
If all went well, your users Facebook wall should look something like this:

My test users Facebook wall
I hope that with this, you have a good understanding on how Facebook’s Graph API works. Start trying to call other objects and play with different extended permissions. The Facebook team did a great job in providing us with the PHP SDK to make this so extremely easy so thumbs up to them. If you have any question/comments, just post them below.








#1 by Denis on December 5, 2010 - 7:33 am
Quote
Perfect article! Everything is understandable and works. I have only one question. How to post to application wall directly as application owner?
For example i need to feed news to wall as application owner, not as simple user etc.
Thanks
Keep it going, very good work.
#2 by Joey on December 6, 2010 - 10:58 am
Quote
I’m glad you enjoyed the article. I may not be understanding the question correctly, but in this example I was the application owner in the sense that I created the application under the same account I used to authenticate and modify.
#3 by bibek on February 3, 2011 - 4:49 am
Quote
Is there any way to show only album’s cover picture instead of showing all images..?
Thank you
#4 by Joey on February 16, 2011 - 3:47 pm
Quote
You can by access the picture connection instead of the photos connection. In the docs: http://developers.facebook.com/docs/reference/api/album/ it mentions that picture is the cover image url.
#5 by kenny on December 21, 2010 - 2:13 pm
Quote
From what I have found you have to include the access token for that Page or Application https://graph.facebook.com/me/accounts?access_token=ACCESS TOKEN]
Then when you call it in your api
$statusUpdate = $facebook->api(‘/yoursite/feed’, ‘post’, array(‘access_token’=>[ACCESS TOKEN], ‘picture’=>$picture, ‘link’=> $link, ‘name’=>$name, ‘caption’=>$caption, ‘description’=>$description, ‘message’=> $message, ‘cb’ => ”));
Hope this helps!
#6 by Joey on December 21, 2010 - 3:22 pm
Quote
Hey Kenny, actually when you call the api method, if access_token is not passed as a param, it will be automatically added for you when making a request during the _oauthRequest method call.
#7 by Denis on December 6, 2010 - 7:08 am
Quote
How to upload multiple images in one post would be interesting as well.
To be able to open it in separate window and vote for it etc.
#8 by Joey on December 6, 2010 - 10:59 am
Quote
That’s an interesting one, I’d have to see if you can submit an array of images instead of doing one at a time. Maybe the reference manual has some info on this.
#9 by Kristen on January 13, 2012 - 4:51 pm
Quote
Just wondering if anyone ever found a way around this?
#10 by Marko on December 6, 2010 - 11:45 am
Quote
What about offline_access, so storing authentication some how and revoking it from your application, if session does not exists?
#11 by Joey on December 6, 2010 - 11:54 am
Quote
Marko,
For offline_access you just need to request that extended permission and after authenticating, store your serialized session for later use. I’ll try to add an example of this tonight in my github. The theory is you authenticate, then do something like
// store the session after authenticating
$session = $facebook->getSession();
file_put_contents(‘facebook_session.txt’, serialize($session));
// then load the session
$facebook = new Facebook(array(pass the same config array here as always));
$facebook->setSession(unserialize(file_get_contents(‘facebook_session.txt’)));
I haven’t tried this code, but in theory this should work. Hope this helps.
#12 by Rob Flynn on December 6, 2010 - 4:51 pm
Quote
I can verify that this is the correct way to do it. I store my session in a database and deserialize it into setSession().
#13 by Joey on December 6, 2010 - 4:59 pm
Quote
Thank you for verifying this.
#14 by Denis on December 6, 2010 - 12:20 pm
Quote
It seems there is no way to upload multiple images in one wall post.
But if creating new photo album with description and then upload to it photos.
It should work.
But i’m getting this error when doing this with app session:
$this->view->access_token = explode(‘=’,exec(‘curl -F grant_type=client_credentials -F client_id=”‘.
$this->_facebook_config['app_id'] .’” -F client_secret=”‘. $this->_facebook_config['secret'] .’” https://graph.facebook.com/oauth/access_token‘));
$this->view->access_token = $this->view->access_token[1];
$message = exec(
‘curl -F “access_token=’. $this->view->access_token .’” ‘ .
‘-F “name=testing album” ‘ .
‘https://graph.facebook.com/’. $this->view->app_id .’/albums’
);
echo $message;
{“error”:{“type”:”IDInvalidException”,”message”:”Invalid id: 0 TAAL[BLAME_file]\n”}}
#15 by Joey on December 6, 2010 - 6:40 pm
Quote
Hey Denis, they only thing I notice with your code is the url. Shouldn’t it be graph.facebook.com/me/albums or graph.facebook.com/$profile_id/albums instead of app_id?
Pingback: Torkil Johnsen » Facebook API tutorial with PHP SDK
#16 by Denis on December 7, 2010 - 4:19 am
Quote
{“error”:{“type”:”OAuthException”,”message”:”An active access token must be used to query information about the current user.”}}
If i’m setting “me” instead of app_id.
I want to post as %application_name% itself, not as simple %user%(profile).
Thanks Joey for fast response. Moderators on official facebook forum are silent about this…
Guess application is limited to such actions. I’ll try to post with simple profile access token.
But this is a bit stupid, because i want to make an official news feed and if under each news will be some unknown user instead of company name(%app_name%)…
well you got the idea
#17 by Joey on December 7, 2010 - 9:07 am
Quote
Denis, hopefully you can find the solution you are looking for. Doing things as described on this blog, you would see ‘via ‘ as you can see on my screen shot under conclusion. My app’s name is blog post test and the two posts made are labeled ‘via Blog Post Test’.
#18 by posting an event on December 8, 2010 - 8:14 pm
Quote
Anybody have any luck posting an event via the api? How about posting an event to a group or a page?
#19 by Joey on December 8, 2010 - 8:27 pm
Quote
Posting an event would be similar to the examples above. First make sure to request the create_event extended permission. Then call the api passing the name, start_time, end_time. For example:
$facebook->api('/me/events', 'POST', array( 'name' => 'Posting a facebook event from API', 'start_time' => '2010-12-24T20:30:00+0000', 'end_time' => '2010-12-26T20:30:00+0000' ));More info can be found at the event’s reference page: http://developers.facebook.com/docs/reference/api/event (and there you can see the format required for start and end time which is ISO 8601)
Pingback: Facebook App Development Continues « William Barnwell
#20 by Marko on December 12, 2010 - 6:08 am
Quote
Thanx!
At last I had the time to imlement this (offline_access thing) and it worked just like you described it.
Now I’m implementing different features but I’m struggling with documentation. Like for example what parameters I can add to api queries.
like this which I found after extensive googling: “/me/friends?fields=id,name,picture,link”
If anyone knows a good place for this information, please share the link?
br, Marko
#21 by Pierre Husted Sigvardsen on December 13, 2010 - 5:45 pm
Quote
THANKS A LOT!!!
This article really helped me.
I’ve been reading 6 or 7 articles about Graph API and PHP the last couple of days, and none of them made any sense.
But your excellent examples helped me, and now I’ve got a small sample-app up and running.
Thanks again!
#22 by Sam on December 17, 2010 - 2:35 am
Quote
Just a quick question.. With your code I can access my app, everything works fine. Now, if a fellow ‘developer’ was to access the page (app in sandbox mode, friend added as developer) he would get this “Error while loading page from Brewspy.com”. I’ve even tried setting up testing accounts, and going out of sandbox mode.. What am I missing?
#23 by Joey on December 17, 2010 - 9:48 am
Quote
Hey Sam, I’m not too sure I understand the question. I haven’t done much more with Facebook other than what I wrote here. What do you mean by ‘friend added as developer’? Also, when you say access the page, do you mean the app?
#24 by Sam on December 17, 2010 - 11:40 am
Quote
Hello and thanks for getting back to me.
Theres a sandox feature (which you are probably aware of) in facebook for your app. Now to let other people access your app (friend) you need to add them as developer. While the app is in sandbox mode no one can access it or see your interaction (unless you add them). I have also taken it out of sandbox mode, and whenever you access the app with someone else’s account, it appears broken (“Error while loading page from Brewspy.com”). But, if you are on the creators account (my account) the app works perfect.
#25 by Joey on December 17, 2010 - 11:44 am
Quote
So if person A creates the app and then person A users their credentials to log into the app it works but if person A creates the app and then person B authenticates it doesn’t work?
#26 by Sam on December 17, 2010 - 11:59 am
Quote
Yes, person(s):
A : Created app, app is fully functional and posts feeds
B : Tries to access app, see’s the ‘app’, but it appears broken. Can see feeds on friends wall created by the app.
Actually now that you mention it, I remember authenticating my account, but I did not see the authenticate dialog on any of my friends accounts.. I haven’t really changed anything with authenticating..
#27 by Joey on December 17, 2010 - 12:03 pm
Quote
I wonder if the app is still trying to use the original users authentication token. Unless you authenticate with the new user, the app should not be allowed to post to that users wall. Is a session being reused from a db/cookie/etc?
#28 by Sam on December 17, 2010 - 12:48 pm
Quote
Odd.. I relocated my app on my server and redirected the app urls and it is working now.. Thanks for your help!
#29 by Janith on December 18, 2010 - 1:47 am
Quote
Wow! I have been trying to get this thing working for a long time! Thanks a million for the nice article! VERY helpful!
#30 by Rob on December 19, 2010 - 9:28 am
Quote
Great article! I’ve been searching all over the internet for someone who is capable of explaining the facebook graph api. Thanks buddy, you got me rolling!
#31 by Benjo on December 19, 2010 - 11:23 am
Quote
Hi Joey,
I’m having problems with retrieving my own albums. I was just wondering how am I going to retrieve my own albums. If I used the request url https://graph.facebook.com/me/albums, I would be retrieving the albums of the viewer of my website, but when I use https://graph.facebook.com/bsilver10/albums(my album with my username), I was required to use an access token. But I want my albums to be viewed without my visitors logging into my website via facebook connect. Thank you in advance, I hope my explanation is clear.
By the way.. my goal is:
List my albums in a page in my website.
Thanks again
#32 by Joey on December 20, 2010 - 9:35 am
Quote
Benjo,
This app will retrieve the albums of ‘me’, me being the user who authenticated and authorized access to their account. From what you are saying, that should be you. You should be able to authenticate once, save that token, and reuse it on your site without anyone else needing any access from facebook. So you create a php page that you access on your browser and authenticate. Then store that session token in a file or in a db. Then on your website, use code that loads your albums using the token you stored so no further authentication is required by your users. I hope this makes sense.
Joey
#33 by Benjo on December 20, 2010 - 10:02 am
Quote
Hi Joey,
Thanks! I’ll try that. I’m just wondering about the expiration of the token, is there an expiration?
Thanks again! Really appreciate it!
#34 by Joey on December 20, 2010 - 10:08 am
Quote
Yes, but you can use the offline_access extended permission to prevent the token from expiring. More info on this topic is covered on one of the comments above.
#35 by n8nie on December 21, 2010 - 4:19 am
Quote
Hi…
I’m creating an app to view all photos from my albums…I’ve read your tutorial but don’t quite understand… the flow…
Frankly, I am a php/facebook dummy…i really need step by step guidance…
P/S : where do u declare this “me”
$albums = $facebook->api(‘/me/albums’);
#36 by Joey on December 21, 2010 - 9:35 am
Quote
Hi, the examples on this post should allow you to do what you are trying to do. Which part is confusing to see if I can clear that up. The ‘me’ part taken from Facebook:
“Additionally, there is a special identifier me which refers to the current user. So the URL https://graph.facebook.com/me returns the active user’s profile.”
So by using /me in the url, you are referring to the current authenticated user.
#37 by Benjo on December 21, 2010 - 8:12 pm
Quote
Hi, thanks again for the solution. I didn’t get it working at first. I was just saving the token for the request, it turns out that I have to save the whole session, so I followed the thing about the saving the session string on my class and loads it whenever I request from facebook. Now it’s up and running. Thanks again! Another thing, about the serialize and unserialize, I used json decode for use in the PHP SDK, and got an array that fits to the setSession function.
Great tutorial! Thank you very much!
#38 by n8nie on December 21, 2010 - 8:32 pm
Quote
Hi..
Thks for the prompt reply.I’ve tried out the examples that you have provided .The problem now is I always getting this JSON error (see as below)…I’ve installed the latest php sdk….
P/S:I’m using a free public server to host my files.
Error:-
===================================
Fatal error: Uncaught exception ‘Exception’ with message ‘Facebook needs the JSON PHP extension.’
=====================================
#39 by Joey on December 22, 2010 - 9:16 am
Quote
It seems like your public server doesn’t have the JSON extension turned on for PHP. Check your phpinfo and search for JSON. I assume it won’t be listed or it’s not enabled. Unfortunately, you’ll have to try another server or ask them to turn it on.
#40 by luciano on December 23, 2010 - 7:06 pm
Quote
APP Facebook prueba
require_once “config.php”;
// Funcion para publicar un mensaje en tu muro
var publish3 = function () {
$img = realpath(“http://img683.imageshack.us/img683/7668/regalosdenavidad.jpg”);
// allow uploads
$facebook->setFileUploadSupport(“http://” . $_SERVER["SERVER_NAME"]);
// add a status message
$photo = $facebook->api(“/me/photos”, “POST”,
array(
“source” => “@” . $img,
“message” => “This photo came from my app.”
)
);
var_dump($photo);
}
Que estoy haciendo mal?
Al apretar el boton no publica la imagen en el muro.
(“http://” . $_SERVER["SERVER_NAME"]); que devo colocar aca?
La imagen la guarde en http://imageshack.us
#41 by Joey on December 23, 2010 - 10:57 pm
Quote
Luciano,
Lo que pasa es que $img = realpath() deberia ser un path a una foto en tu system local, no un url a una foto en otro servidor. Lo que puedes hacer es save la foto en tu systema y entonces usar el codigo que estas tratando. Por ejemplo:
$img = file_get_contents(“http://img683.imageshack.us/img683/7668/regalosdenavidad.jpg”);
entonces en el array(
“source” => $img, // sin el @
“message” => “tu mensaje”
)
Trata esto haber si funciona.
Joey
#42 by Ahmad on December 24, 2010 - 10:32 am
Quote
Hi Joey,
Nice and clean work you have done here
I’m having a problem with Add_photo part
when I run the code I receive this error:
Fatal error: Uncaught CurlException: 26: failed creating formpost data thrown in /html/fb/facebook-php-sdk/src/facebook.php on line 622
The photo I want to upload already exist in the same directory on the server
Any idea ?
#43 by Joey on January 3, 2011 - 9:17 am
Quote
Does it only happen with the photo that is already in the server directory? If so, maybe it’s a permissions issue. Delete the photo and try again? If that’s not the problem, can you post your code to see if anything stands out.
#44 by Faizan on December 26, 2010 - 4:42 am
Quote
The tutorial is great and it help me creating events through graph api but i m not able to add a profile picture for that event..can u please give me a hint on how to do that..
Fatal error: Uncaught OAuthException: (#324) Requires upload file thrown in /home/mchinoy/public_html/dev/library/facebook.php on line 543
And this is the error which i am having
Thanks in advance
Faizan
#45 by Joey on January 3, 2011 - 9:22 am
Quote
Make sure you are requesting the correct extended permissions to modify the profile picture. Next make sure you are making a post instead of a get and finally make sure you are calling $facebook->setFileUploadSupport to allow uploading of the image. See if that helps and if not can you show your code to look further into this problem.
#46 by Aman on December 28, 2010 - 5:46 pm
Quote
Hey Joey,
nice work. My problem though is this code is just not working for me
. I have just one index.php file which has everything. So after setting the appid and secret at the top of the file and then instantiating the Facebook instance, I do the following:
if(is_null($facebook->getUser()))
{
header(“Location:{$facebook->getLoginUrl(array(‘req_perms’ => ‘user_status,publish_stream,user_photos’))}”);
exit;
}
else
{
echo “OK so the getUser() is not null”;
$me = $facebook->api(‘me’);
print “This gets printed”;
}
The first echo (in the else block) works fine, because i had authenticated the app, but the second line for some reason does not work as expected and neither does the third line. If I remove the call to the api() method though, as u can imagine the third line prints. This i my first FB app that i m trying to write and i m struggling with sheer basics. I would reall appreciate if u can shed some light on this.
Thanks
#47 by Joey on January 3, 2011 - 8:56 am
Quote
Aman, what error message are you receiving? The only thing I can think of is adding a backslash to the api call. Instead of api(“me”) try api(“/me”).
#48 by nofy on December 29, 2010 - 1:24 pm
Quote
Sir joey how can i access the list of friends. can you create sample php code tnx
#49 by Joey on January 3, 2011 - 9:33 am
Quote
Sure, I’ll try to get one up on my github in the next day or two.
#50 by Joey on January 3, 2011 - 10:26 pm
Quote
All that was needed for this is:
$friends = $facebook->api(‘/me/friends’);
#51 by sahilsk on December 30, 2010 - 5:23 am
Quote
hi,
When I generate a login URL using Facebook PHP SDK using your code snippet, I see the “Request for permission” with allow and dont allow in my web site, But when I embed the same app inside a canvas as an iFrame in my canvas application, it only shows a logo of facebook, and doesnt show the “Request for permissions”.
“request for permissions” comes after clicking on that logo.
solution:
instead of using php redirect , if i use javascript (top.location.href ) to redirect my page, it works well but could you please give a php solution to this problem??
#52 by Joey on January 3, 2011 - 9:05 am
Quote
I’m a bit confused as to why you would see a facebook logo that you have to click on first to see the request for permission page. Do you have an example of this to have a better idea of what is happening? Instead of using an iFrame, can you use a JS modal window to show the Facebook authentication part?
#53 by Mike on January 3, 2011 - 8:58 pm
Quote
If you look at Facebooks documentations on this topic, they don’t even user their php-sdk, which really stinks, but the code sample they use specifically uses top.location.href. You should be able to find the link here:
http://developers.facebook.com/docs/guides/canvas
I don’t think it’s the best solution to use JS but I’ll take it for now.
#54 by mctaco on January 2, 2011 - 3:40 am
Quote
Muy buen post para entender cómo funciona la Graph API, muchas gracias! También qué amable eres por tomarte el tiempo de responder a las preguntas que te hacen en este post
#55 by Joey on January 3, 2011 - 9:12 am
Quote
Es mi placer.
#56 by Dude on January 5, 2011 - 5:07 pm
Quote
Thanks for the article! Good job explaining all the pieces.
I had been pulling my hair out for hours until I realized I had forgotten the fb_ca_chain_bundle.crt file. Doh!
#57 by Joey on January 5, 2011 - 5:33 pm
Quote
I’m glad you got it working. Others having issues should make sure to check this as well.
#58 by Dane Morgan on January 6, 2011 - 3:00 am
Quote
You would think a blog with this post on it would have a like button somwhere…
#59 by Joey on January 6, 2011 - 8:59 am
Quote
touche
#60 by Noha on January 6, 2011 - 3:32 pm
Quote
hi,
” Couldn’t resolve host ‘graph.facebook.com’ [type] => CurlException ) ”
I’ve this exception thrown in my face
when i used try – catch technique on the API () method
and i checked that cURL is enabled on my server
Any ideas why is that ??
thanks in advance
Noha
#61 by Joey on January 6, 2011 - 4:06 pm
Quote
Noha, could you post your code to get a better idea of what could be happening?
#62 by Noha on January 6, 2011 - 5:37 pm
Quote
Thanks for yr quick reply
here is my code :
<?php
try{
require 'facebook.php';
echo ' This is working’;
}
catch(Exception $o){
echo ”;
print_r($o);
echo ”;
}
$facebook = new Facebook(array(
‘appId’ => “xxxxxx”,
‘secret’ => “xxxxxxx”,
‘cookie’ => true
));
try{
if(is_null($facebook->getUser()))
{
header(“Location:{$facebook->getLoginUrl(array(‘req_perms’ => ‘user_status,publish_stream,user_photos’))}”);
exit;
}
echo ‘getUser is working’;
}
catch (FacebookApiException $e){
print_r($e);
echo’NOT working’;
}
try{
$status = $facebook->api(‘/me/feed’, ‘POST’, array(‘message’ => ‘This post came from my app.’));
var_dump($status);
echo ‘This is working’;
}
catch (FacebookApiException $e){
print_r($e);
}
?>
when i try : apps.facebook.com/fuoegfriends/
i get this exception error msg
i’m on ryanhost free domain till i get my premium account
i’m thinking may be because i’m on a free web host may be it is limited and remote connection to facebook isn’t enabled
#63 by Joey on January 9, 2011 - 9:33 pm
Quote
I don’t see anything that stands out. You may be right on your server not allowing access. Here is some info from someone having the similar problem, maybe this will help in determining if it is your server not permitting access.
http://forum.developers.facebook.net/viewtopic.php?pid=241978
#64 by Pride Grimm on January 8, 2011 - 10:21 pm
Quote
Hello. I’m very new to the facebook platform. I’m following your tutorial step-by-step. I’ve got the config.php and I downloaded your index.php. When I run the index.php I get the following error:
Warning: Cannot modify header information – headers already sent by (output started at /home/pdgrimm/public_html/fb/index.php:2) in /home/pdgrimm/public_html/fb/config.php on line 15
Am I missing something stupid? I have the library files (facebook.php and the crt file). I am running the fine in DW cs5 on localhost, and on a server. The error can be seen at this practice app.
http://apps.facebook.com/pridegrimm/
#65 by Joey on January 9, 2011 - 7:03 pm
Quote
My first guess is that your app is throwing an error or warning and because it has, it can’t do a header redirect. I would comment out the header redirect part and check to see if there is an error or warning being displayed. Make sure to have error reporting on:
// Report all PHP errors
error_reporting(-1);
#66 by rolcho on March 3, 2011 - 8:41 pm
Quote
Hi Pride,
I was getting the exact same problem. I fixed my issue by removing all the HTML code (i.e. just have the code ony) in the config.php file.
Hope this helps.
Cheers,
#67 by Noha on January 10, 2011 - 6:55 am
Quote
Well the weirdest thing has just happened ! the server is officially down ! Everything is against a young mommy who tries to be some developer
) and when i do some progress I will let u no
Anyway thanks for your valuable time with a beginner
#68 by Joey on January 10, 2011 - 10:32 pm
Quote
I wish you luck with your development and let me know if you have any other questions.
#69 by Pride Grimm on January 10, 2011 - 4:42 pm
Quote
Joey, if I get on your nerves, let me know. I am really trying to learn this, but have never worked with an API like this. I’m a web programmer/flash. I commented out the redirect and now get this
Strict Standards: Unknown: It is not safe to rely on the system’s timezone settings. Please use the date.timezone setting, the TZ environment variable or the date_default_timezone_set() function. In case you used any of those methods and you are still getting this warning, you most likely misspelled the timezone identifier. We selected ‘America/Chicago’ for ‘CST/-6.0/no DST’ instead in Unknown on line 0
Fatal error: Uncaught OAuthException: An active access token must be used to query information about the current user. thrown in /home/pdgrimm/public_html/fb/library/facebook.php on line 453
#70 by Joey on January 10, 2011 - 4:48 pm
Quote
It’s no problem. The reason you are getting that warning is because your environment doesn’t have a default time zone set. Here is more information: http://docs.php.net/manual/en/function.date-default-timezone-set.php. Add the following line of code to the top of your file after the open php tag:
date_default_timezone_set(‘America/New_York’); // I’m using this time zone, yours may differ depending on where you live.The link above has a list of all supported time zones.
#71 by Pride Grimm on January 10, 2011 - 8:36 pm
Quote
That answered that. There were two errors here is the other one:
Fatal error: Uncaught OAuthException: An active access token must be used to query information about the current user. thrown in /home/pdgrimm/public_html/fb/library/facebook.php on line 453
The time zone thing is not in the tutorial. Is that something that isn’t always required, or is it something that is in the setup or php.ini file that I didn’t change. I am relatively familiar with php, but still learning. Thanks for your patience.
#72 by Joey on January 10, 2011 - 10:31 pm
Quote
You should still be getting the facebook authentication error. Since you commented out the header redirect line, you application won’t redirect to authenticate therefor you can’t access information about the current user. Uncomment the header line and try again. Since you were getting a warning before, it was probably not letting you redirect but now that you added the timezone code, you should be fine.
The timezone warning was added to some version of PHP but I don’t remember which. You have to either declare it for each of your application or just set it once in your php.ini file. If you open the php.ini file and add the following line, it’ll set it for all your applications:
date.timezone=”America/New_York”
#73 by Friedrich Zohmann on January 11, 2011 - 3:18 am
Quote
I tried the code above with e.g. the user.php. What happens is that when I m not logged in at Facebook, I m correctly redirected to the login screen. After logging in there, I always land in an infinite redirection loop. Do you know whats wrong here?
thanks
#74 by Joey on January 16, 2011 - 6:57 pm
Quote
Friedrich, did you figure out the problem? If not, can you post your code. It seems like something might not be checking correctly.
#75 by Pride Grimm on January 11, 2011 - 12:53 pm
Quote
I’ll do that. Why will a redirect not be allowed if there is a timezone discrepancy?
#76 by Joey on January 11, 2011 - 2:38 pm
Quote
In order to do a header redirect in PHP, nothing can outputted prior to trying calling header(). In your case, since the timezone wasn’t set, a warning was being outputted so by the time you tried to do a header redirect, you would get an error saying there was already some output.
#77 by Molham on October 1, 2011 - 11:57 am
Quote
i am trying to use something different with i frame tab which you can upload your image from https://www.facebook.com/DalilackAds?sk=app_203351739677351
and also share it with your friends
is there any thing similar to that ?
please help!
#78 by Joey on October 5, 2011 - 8:44 am
Quote
Molham, the only advice I have when uploading a photo was that I was not able to upload a photo that was stored in facebook. I first had to download the photo to a different location and then upload it from there. Hope this helps.
#79 by Noha on January 12, 2011 - 2:24 am
Quote
IT WORKED>… Yuppppiiii .. it was the server’s problem so i changed the host hhh
Thanks so much and wait to see my first App
#80 by Joey on January 12, 2011 - 1:23 pm
Quote
Congrats! I’m glad you got it working – all the effort paid off.
#81 by Max on January 12, 2011 - 4:42 am
Quote
Just got it! it’s working… so I figure now: further studies how to put all these code to work inside my app, so they can generate my users info needed!
#82 by Anton on January 12, 2011 - 5:27 pm
Quote
Hi Joey!
First of all I want to say that I loved your guide, its what got me started on developing facebook applications, i do however have some questions and I hope you have an answer!
I successfully managed to update my status with the facebook app, but I know there are many applications that do it in a different way. What they do is that they give the user a fancy pop-up box containing the users result, often the way it will be displayed on their wall together with a share/don’t share button. Now I am not wondering about the popup box, but I am wondering about the way this happens. If you check your facebook, you will probably see some of theese results, but they appear only on the users wall not as a status update, they are also formatted differently. How can I publish this to the user’s wall (not status update) in my facebook app?
I hope you understood what I meant and again thanks for the tutorial,
-Anton
#83 by Joey on January 16, 2011 - 6:56 pm
Quote
Hey Anton, I haven’t done much more than what I posted here with Facebook. Posting a status update updates your wall so I’m not sure I understand the question. Maybe look at making a post instead of a status to see if you get the results you want. If you pass it an image/link/description/etc it’ll be formatted differently: http://developers.facebook.com/docs/reference/api/post/
#84 by iffi on January 13, 2011 - 3:25 am
Quote
Hi Joey,
Please take visit my very new app. I have read your article and try it out. But i cant get it done. Please take a look and tell what happen with it.
I just changed key from your script and nothing.
http://apps.facebook.com/mughals/
Thanks in advance.
iffi
#85 by Joey on January 16, 2011 - 6:59 pm
Quote
iffi, I checked your link and it says there is a syntax error on line 35. Can you check and see if there a typo in that line?
#86 by Jeroen on January 14, 2011 - 2:09 pm
Quote
Hello, I would just like your opinion about my code. It all seems to work fine but I would like to know if this is the right aproach to “talk” with facebook or not. If not where could I improve and why?
Thanks!
$application_id,
‘secret’ => $application_secret,
‘cookie’ => true
));
# Get login url from Facebook
$loginurl = $facebook->getLoginUrl(array(‘req_perms’ => ‘email,user_likes’));
# Let’s see if we have an active session
$session = $facebook->getSession();
if(!empty($session)) {
# Active session
$userid = $facebook->getUser();
if (is_null($userid)) {
# No user information availble yet
header(“Location: {$loginurl} “);
exit;
} else {
# All is okay now, we can start requesting extended user information from Facebook
try {
# Lets get user information, data is returned serialized with JSON
$user = $facebook->api(‘/me’);
echo “”;
print_r($user);
echo “”;
} catch (FacebookApiException $e) {
# Ops an error occured, most likely we are not authorized yet…
$url = $facebook->getLoginUrl(array(‘req_perms’ => ‘email,user_likes’));
header(“Location: {$loginurl} “);
exit;
}
}
} else {
# There’s no active session, let’s generate one
header(“Location: {$loginurl} “);
exit;
}
?>
#87 by Joey on January 16, 2011 - 7:13 pm
Quote
Jeroen, as far as I can tell the code looks good. ->getUser() is already checking ->getSession() so I don’t see a need to check both which would save you a couple lines of code. Finally, since you declare $loginurl, you can probably remove the extra line declaring $url in your catch.
#88 by Pride Grimm on January 16, 2011 - 2:28 pm
Quote
I got it working. Thanks for your help Joey. I’m going on with tutorial.
#89 by pradeep on June 27, 2011 - 10:30 am
Quote
hey how did u get it working. i am also getting the same error as of urs.
i am getting error like Fatal error: Uncaught OAuthException: An active access token must be used to query information about the current user. thrown in /home/abcd/public_html/library/base_facebook.php on line 988
#90 by Friedrich Zohmann on January 17, 2011 - 12:59 am
Quote
Hi Joey,
Do you know if there is a replacement in the new Graph API for these calls from the old REST API:
$facebook->api_client->users_isAppUser($user_id);
$facebook->api_client->users_hasAppPermission(‘publish_stream’, $user_id);
The 1st one checks if a user has authorized the APP and the 2nd one checks if the user already has authorized the “posting on wall” permission for the APP.
I dont know how I can check that with the new PHP SDK.
thanks, Friedrich
#91 by Joey on January 19, 2011 - 8:58 am
Quote
Friedrich,
You can still use the rest api with the new SDK. If you open up the facebook.php file from the SDK and scroll down to the method ‘getApiUrls’, you’ll see a list of all the available methods you can call. We still use $facebook->api() to call these, all you need to do is pass an array with a method key setting the actual method you want to call as the value. Here is an example:
$return = $facebook->api( array( ‘method’ => ‘users.isappuser’ ) );
Hope this helps and I went ahead and added this example to my github.
#92 by Peter G on January 19, 2011 - 5:21 am
Quote
Hi Joey, thanks for this amazing post man! Really helped me a lot to get an idea on how to use the facebook php SDK!!!
Would like to ask if I want to use this as an “inside facebook application” in which I mean not a connent app but an application runnning inside facebook, what do I have to change?
I’ve tried it as it is and got a facebook logo inside my canvas and nothing else!
Thanks again for the post and keep up the good work!
Cheers,
Peter
#93 by Joey on January 19, 2011 - 8:01 pm
Quote
Hey Peter, I’m not sure I understand what you mean. To be honest, my first time using facebook was when I wrote this blog post right after writing a small ‘app’. What do you mean by an ‘inside facebook application’? Can you point me in the right direction?
#94 by Friedrich Zohmann on January 22, 2011 - 11:11 am
Quote
Thanks Joey, you advise helped me.
#95 by Joey on January 23, 2011 - 12:17 pm
Quote
I’m glad I could help!
#96 by Sezgin on January 23, 2011 - 8:33 am
Quote
Hi.
This code try..
$app_id=’myid’; // Application ID;
$app_secret=’mysecret’; // Application Secret ID;
$app_key=’mykey’; // Application Key;
$facebook= new Facebook(array(
‘appId’=>$app_id,
‘secret’=>$app_secret,
‘cookie’=>true,
‘fileUpload’=>true,
));
$img = realpath(“C:\\image.jpg”);
// allow uploads
$facebook->setFileUploadSupport(“http://” . $_SERVER['SERVER_NAME']);
// add a status message
$photo = $facebook->api(‘/me/photos’, ‘POST’,
array(
‘source’ => ‘@’ . $img,
‘message’ => ‘This photo came from my app.’
)
);
var_dump($photo);
But this error message:
Fatal error: Uncaught CurlException: 26: failed creating formpost data thrown in /home/mydomain/public_html/myapp/facebook.php on line 622
#97 by Joey on January 25, 2011 - 9:28 am
Quote
Sezgin, a couple people have mentioned they had that problem. I doubled checked the comments and I don’t see what was the solution. The first few things to try would be to make sure curl is turned on in your server. I assume that since you get that messages it’s on. Next is to make sure your server can communicate with graph.facebook.com. Finally, make sure that the file image.jpg exists on your servers c:\ drive. In this example we aren’t uploading a file from our machine to this php script, we are telling the php script to load a file that should already be in the server located at c:\. I assume from your error message that your file should be in your users public_html folder.
#98 by ebooks on August 12, 2011 - 5:39 am
Quote
check your facebook init.
$facebook = new Facebook(array(
‘appId’ => $app_id,
‘secret’ => $app_secret,
‘cookie’ => true ,
‘fileUpload’ => true //add this
));
works for me. hope it helps
#99 by Kenneth on January 24, 2011 - 6:43 pm
Quote
I’m starting to get a serious headache. I’ve tried several tutorials, also the facebook standard examples from the php-sdk, nothing seems to work.
I’ve tried your method, step by step and immediatly the full downloaded script. Nothing works as it should
So I tried the simple things. Your config.php and user.php is not even working properly. I’ve written a blog on http://kdegussem.us/?p=120 about it and my findings and the example of your config.php and user.php are on http://ilike.rooty.be/fbtest2/index.php
I’ve changed the user.php to index.php for indexing reasons.
Can you have a look and shed some insight on my problem?
#100 by Joey on January 25, 2011 - 9:17 am
Quote
Kenneth, I clicked on the example link and get a server error but no php information. I recommend turning on the display of errors on php to see what is break or look at your php error log. Try adding error_reporting(-1) to the top of your config.php file and reload the index.php page to see if you get some more helpful feedback. Do you know if you have the curl extension turned on in your server? If you aren’t sure, check your phpinfo() to make sure.
#101 by Kenneth on January 25, 2011 - 8:17 pm
Quote
I checked the phpinfo() and as suspected it is installed (parsed ini /etc/php5/apache2/conf.d/curl.ini).
I’ve also checked my error_log is something really odd
[Mon Jan 24 17:11:43 2011] [error] [client xx.226.98.78] File does not exist: /var/www/vhosts/rooty.be/ilike/favicon.ico, referer: http://ilike.rooty.be/fbtest/example.php
That leaves me really makes me ask why he needs a favicon in the first place.
I’ve added the error_reporting(-1); to the config.php aswell and the results are the same. Although I have found out that the server error only happens in the Meltrock browser.
Oh also JSON is enabled.
#102 by Joey on January 27, 2011 - 9:10 am
Quote
Kenneth, I’m not familiar with the Meltrock browser, does that mean this is working on other browsers like Chrome? About the favicon, that’s pretty standard. Browsers usually request that file when loading a webpage to display the proper icon, if you don’t have that file, you’ll get a 404 in your logs each time. Don’t worry about that error though, it’s shouldn’t affect your app. Next, have you found any other error specific to your facebook php files in the error logs? We need to find some descriptive error to know what is breaking. Can you try your code in another hosting environment just to see if that fixes your problem?