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.
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:
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
require_once 'library/facebook.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
require_once 'config.php';
$me = $facebook->api('/me');
var_dump($me);
If you run this code you get something like this:
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
require_once 'config.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
require_once 'config.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
require_once 'config.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
require_once 'config.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:
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.
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.
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.
Is there any way to show only album’s cover picture instead of showing all images..?
Thank you
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.
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=%5BACCESS 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!
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.
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.
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.
Just wondering if anyone ever found a way around this?
What about offline_access, so storing authentication some how and revoking it from your application, if session does not exists?
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.
I can verify that this is the correct way to do it. I store my session in a database and deserialize it into setSession().
Thank you for verifying this.
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”}}
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?
{“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 😉
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’.
Anybody have any luck posting an event via the api? How about posting an event to a group or a page?
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:
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)
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
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! 🙂
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?
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?
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.
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?
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..
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?
Odd.. I relocated my app on my server and redirected the app urls and it is working now.. Thanks for your help!
Wow! I have been trying to get this thing working for a long time! Thanks a million for the nice article! VERY helpful!
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!
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
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
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!
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.
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’);
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.
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!
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.’
=====================================
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.
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
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
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 ? 🙁
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.
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
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.
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
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”).
Sir joey how can i access the list of friends. can you create sample php code tnx
Sure, I’ll try to get one up on my github in the next day or two.
All that was needed for this is:
$friends = $facebook->api(‘/me/friends’);
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??
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?
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.
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
Es mi placer.
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!
I’m glad you got it working. Others having issues should make sure to check this as well.
You would think a blog with this post on it would have a like button somwhere… 😉
touche
hi,
I’ve this exception thrown in my face 🙁 ” Couldn’t resolve host ‘graph.facebook.com’ [type] => CurlException ) ”
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
Noha, could you post your code to get a better idea of what could be happening?
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
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
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/
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);
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,
Well the weirdest thing has just happened ! the server is officially down ! Everything is against a young mommy who tries to be some developer 😀
Anyway thanks for your valuable time with a beginner :)) and when i do some progress I will let u no 🙂
I wish you luck with your development and let me know if you have any other questions.
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
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.
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.
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”
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
Friedrich, did you figure out the problem? If not, can you post your code. It seems like something might not be checking correctly.
I’ll do that. Why will a redirect not be allowed if there is a timezone discrepancy?
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.
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!
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.
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 😉
Congrats! I’m glad you got it working – all the effort paid off.
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!
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
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/
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
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?
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;
}
?>
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.
I got it working. Thanks for your help Joey. I’m going on with tutorial.
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
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
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.
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
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?
Thanks Joey, you advise helped me.
I’m glad I could help!
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
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.
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
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?
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.
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.
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?
Hi Joey…
Is it possible to grab posted pictures from our facebook walls??
Appreciate if you could guide me.
You should be able to. First get all the users posts (http://developers.facebook.com/docs/reference/api/user/ ex: /user/posts/), then loop through all the posts (http://developers.facebook.com/docs/reference/api/post/) and if they have an picture property grab that image using the link provided by the picture property on each post.
Hi,
Nice tut! I got it working just great. I want to know how to make a form on the add status page. Can you guide me please? 🙂
Thanks!
Al, do you mean a regular HTML form? If so, try this: http://www.w3schools.com/html/html_forms.asp
Hi Joey…
I try to list out all the feeds.This is my code:-
$feed = $facebook->api(‘/me/feed’);
foreach($feed[‘data’] as $feeds)
{
echo $feeds[“message”], “”;
}
But i got an error:-
Warning: Division by zero
Fatal error: Uncaught GraphMethodException: Unsupported get request. thrown
Actually..I’m still new and learning PHP & Graph API
Suzane, does the status example above work? If you try loading /me/statuses does that work or neither work?
Hi Joey..
$feed = $facebook->api(‘/me/feed’);
foreach($feed[‘data’] as $feeds)
{}
Now i didnt get any error…but it didnt display anything…
I try to list out the id of the feeds but it didnt display anything……
echo $feeds[‘id’], “”;
I test the graph api in this console its able to display.
http://app.apigee.com/console
Are you in the developer sandbox mode? Seems like this was causing others issues when trying to load data.
Got a q for ya about access (I don’t think it’s a privacy problem, but that could be the issue).
In the test console, when I run: uid=1146 and fields=work_history, I get this response:
“uid”: 1146,
“work_history”: [
{
“location”: {
“city”: “”,
“state”: “”
},
“company_name”: “The Center for Effective Philanthropy”,
“description”: “”,
“start_date”: “0000-00”,
“end_date”: “0000-00″
}
]
which is what I expect.
When I run my own code (with my own UID), that works, too. But, when I run my code from my server, with the UID above (1146), I can’t ONLY get access to the most basic info (name, location, etc…). Any idea why this is?
$params = array(‘method’=>”users.getinfo”,”uids”=>1146,”fields”=>”uid,name,work_history”);
$worktest = $facebook->api($params);
uid and name will come back, but work_history won’t.
Andy, like you mentioned, have you authenticated in all environments using the same permissions? To retrieve work information requires the user_work_history permission when authenticating. I recommend removing the app from your authenticated lists of app and authenticating again.
Hello Joey,
Great article, I just have a couple hiccups. First of all, I am having issues with special characters in posts such as ç, ö, ş, ü. When I post a message in the feed with the following code, special characters are simply not displayed.
$status = $facebook->api(‘/me/feed’, ‘POST’, array(‘message’ => ‘öçşiğü’));
The message displayed is: “i”
If I replace the special characters with the html code entities, then the html codes get displayed. I also tried the \u00e7 but again, the code is displayed. Do you know how they should be input in order to display properly?
Another question I have is, I am displaying the login to facebook link on my website, that takes the user to the “allow” page of facebook (in the same window, not in a separate dialog window), but after they click on allow, facebook redirects the user to my page that is opened in my canvas (a frame within facebook). Is there a way to redirect the user to my website (without frames) after the allow page?
Thanks a lot and the following is my full code:
$appId, ‘secret’=>$apiSecret, ‘cookie’=>true,));
$session = $facebook->getSession();
$fbme = null;
if ($session) {
try {
$fbme = $facebook->api(‘/me’);
} catch (FacebookApiException $e) {
error_log($e);
}
}
if (!$fbme) {
$loginUrl = $facebook->getLoginUrl(array(‘canvas’ => 1,
‘fbconnect’ => 0,
‘req_perms’ => ‘publish_stream’,
‘next’ => ‘http://www.gozlukdukkani.com/raffles/deneme/deneme.php’,
‘cancel_url’ => ‘http://www.gozlukdukkani.com’ ));
echo ‘Giriş‘;
}
else {
$status = $facebook->api(‘/me/feed’, ‘POST’, array(‘message’ => ‘öçşiğü’));
echo ‘oldu’;
}
Well. . .
I am an idiot. Setting canvas to 0 and fbconnect to 1 solved that problem. Everything works perfectly now.
Sorry to bother you guys,
Ali
Ali, I’m glad you were able to solve your problem. Hopefully this helps others experiencing the same issue.
Hey,
I just found your website and tried a lot of option. But still, writing
#Demande Particulière d’autorisation
$scoped = “user_photos,user_status,publish_stream”;
$facebook = new Facebook(array(
‘appId’ => $app_id,
‘secret’ => $app_secret,
‘cookie’ => true
));
try{
if(is_null($facebook->getUser()))
{
$redirectlocation = $facebook->getLoginUrl(array(
‘req_perms’ => $scoped));
header(“Location:{$redirectlocation}”);
exit;
}
echo ‘getUser is working’;
}
gives to me “The url … is not valid”
L’URL https://www.facebook.com/login.php?cancel_url=http%3A%2F%2Fwww.algorythme.net%2Ffacebook%2F&display=page&fbconnect=1&next=http%3A%2F%2Fwww.algorythme.net%2Ffacebook%2F&return_session=1&session_version=3&v=1.0&req_perms=user_photos%2Cuser_status%2Cpublish_stream n’est pas valide.
http://apps.facebook.com/ownalbumscover/
Could you help me please ? And thanks for your tutorial !
Tybalt, did you figure out your problem? I just went to your link and it’s asking me to authorize your app?
hey I am using offline_access.
i wrote the following code.
access_token retrieved from database.
$attachment = array(
‘access_token’ => $access_token,
);
$facebook = facebookservice_api();
$fbfeed=$facebook->api(‘/me/feed’, ‘GET’, $attachment);
i get blank data
However it works fine if i use /me/home or /me/statuses instead of /me/feed.Any reason why?
However I am able to publish to the feed.
Thanx in advance
Make sure you are logged into fb, then go to the following reference page: http://developers.facebook.com/docs/reference/api/user
Scroll down to connections and click feed on the left hand side. When you go to the next page, does it list all your feeds?
Hi,
Yeah I checked out on this and it does list my feed.However when i replace the token with the one saved in my database,it again shows blank data.No problem as such with the home or statuses thing.I also checked out with your code by replacing /me/statuses with me/feed.Still the same problem.I get blank data.However no such problem when I use statuses or home.Any suggestions.
Also is there any other way by which I can show a user’s friend requests
on my application without using fql.
ok I think i may know what the problem is.Most of the things that i am able to see through /me/home is public stuff.I am not able to see any of my friends stuff.Hence the data which I get by clicking on the /me/home on facebook’s developer page is quite different when i replace the access token with mine.
Thanks in advance.
Someone mentioned that they were having an issue with a blank screen and it ended up them being in the development sandbox, could this be the case with you? As far as the friends request, I don’t see anything in the Graph API documentation that mentions this so I can’t really answer your question. Maybe someone else here knows.
Can u tell how to tag a photo while uploading it?
This should help:
You can tag photos using Graph while uploading them by also submitting a JSON formatted array of tags in the post data. See lifeform’s comment here for more information: http://forum.developers.facebook.net/viewtopic.php?pid=305456#p305456
Dear Joey,
Thanks a lot for your efforts and kindness of writing this page!!
It did help me alot!
thanks! =D
When I am logged in and if I run the config.php file, I am getting a request page. Sometimes this vanishes and takes me to an empty page with facebook icon there.
However, if I am not logged in it says page not found error. I thought it would take me to facebook login page.
Ok I figured it out. I was in sandbox mode. Looks like in Sandbox mode it works differently . But why would that be?
I’m glad you were able to figure out your problem and hopefully this helps others experiencing the same issue. I didn’t use the sandbox so I’m not sure why it’s setup to work differently. We may have to point this problem out to Facebook for them to investigate further.
Thank you for the great article
Hi Joey,
is there any php way to redirect to canvas after adding a tab to a fan page through “http://www.facebook.com/add.php?api_key=APIKEY&pages” ?
i’ve try to find the solution but seems negative
http://forum.developers.facebook.net/viewtopic.php?id=71010
but still got people suggested solution here but it is the old REST API
http://forum.developers.facebook.net/viewtopic.php?id=78687
there’re people say that it can be done if using Javascript SDK’s FB.login.
but is there a way using PHP SDK?
hope to hear from you.
thanks
Regards, Elone.
I wonder if you can try something like:
$url = $facebook->getLoginUrl(array(‘req_perms’ => ‘user_status,publish_stream,user_photos’));
$url .= $url . ‘&redirect_uri=’ . $redirect_url;
tried. work for authentication but not work for adding tab to page using add.php…
Thanks for replying..
This code is great but I am having a problem. Rather than saving the session to a text file I am doing it to a database
$session = $facebook->getSession();
$sessionSerialized = serialize($session);
mysql_query(“update infousr set facebook = ‘$sessionSerialized’ where userid = 1”);
This works fine unless I log out of facebook. Is there a way to keep a token so that even if a user is not logged into facebook my app can post to their profile?
I’ll add an example on how to do this in the next day or two.
Hi,
I have mine access_token(with offline access).
I would like to use mine application without manual-login (server-side ).
I would like to run the application every day (like cron), but
how can i obtain an infinite session key?
Ruggero, I’ll create an example of how to do this and add it to my github or create a new blog post since many have asked this question. It should be up in the next couple days.
Hi Joey,
I developed this api last month or so:
http://apps.facebook.com/verdensbedsteferier/
Everything works well, except that when you logout of FB the sessions arent cleared. i.e. $me still has all the info there. The funny thing is that works fine on IE not any other browser I tested (firefox, chrome, safari). I have some extra code in there for session key so i can post on users wall, but as I said, the issue is the session not being cleared.
Any solution on this?
Thanks
Have you tried logging into your facebook account and removing the app from your list of authorized apps to force an authentication next time you try to access the app? I have some info under the authentication and extended permissions section of the post.
thanks for considering my request , btw I looked into set setFileUploadSupport , it sets the property of type boolean inside it which tells curl to consider ‘@’ symbol , so you can change it to $facebook->setFileUploadSupport(true); in your tutorial.
Ahh thanks, good catch. I’ll have to update that.
Hi, I’ve followed your tutorial, and many other like it but I cant seem to get my app to authorise, it wont even ask. http://apps.facebook.com/miscritsladder/
I’ve tried on 3 different accounts and removed the app from each one. I dont understand what’s going on. can you try the link for me?
The solution here: http://phpfour.com/blog/2010/05/quick-start-on-new-facebook-php-sdk-iframe-based/
Worked for me.
Thanks Justin for providing that link. So it seems that for IFrame apps you need to turn on the canvas option. Hope this helps other experiencing similar issues.
Justin, I’m going to the link you provided and I see a ‘Request for Permission’ Facebook page asking me to authenticate to the Miscrits Ladder app. Seems to be working correctly? It’s requesting to access my basic information.
I love the tutorial everything works great for me!
but is there anyway using status_add.php to get the message being posted look something like this ?
http://i53.tinypic.com/2it0pi8.jpg
A post with a message, link, and image should give you that same result: http://developers.facebook.com/docs/reference/api/post/
Hello joey,
I wanted to tell you that the upload photo to album is working. But one thing, I need to detect the session, it doesnot automatically detect any sessions, but it does when I run before detecting.
define(‘FACEBOOK_APP_ID’, ‘1234);
define(‘FACEBOOK_SECRET’, ‘abcd’);
function get_facebook_cookie($app_id, $app_secret) {
$args = array();
parse_str(trim($_COOKIE[‘fbs_’ . $app_id], ‘\\”‘), $args);
ksort($args);
$payload = ”;
foreach ($args as $key => $value) {
if ($key != ‘sig’) {
$payload .= $key . ‘=’ . $value;
}
}
if (md5($payload . $app_secret) != $args[‘sig’]) {
return null;
}
return $args;
}
$cookie = get_facebook_cookie(FACEBOOK_APP_ID, FACEBOOK_SECRET);
echo print_r($cookie);
I think this is forming the necessary cookie required. How do we form a proper PHP signed request, the example in the PHP SDK does not say anything about the signed request before getting the api? There is no setsignedRequest in facebook.com. Do let me know how to work around this.
I really appreciate your help. Thanks
Nandita
If I understand correctly, you are trying to use cookies to track your session? If so, try $facebook->setCookieSupport(true); before authenticating. But to check if you have a session created you can call $facebook->getSession(); If there is no session established, that method getSession will create one by checking your cookies.
When I use the following:
$url = $facebook->getLoginUrl(array(
‘canvas’ => 1,
‘fbconnect’ => 0,
‘req_prems’ => ‘user_status,publish_stream,user_photos’
));
echo “top.location.href = ‘$url’;”;
I am not prompted for any other user permissions aside from the basic prompt (IE: i’m not being asked about accessing my photo etc)
Thanks
Have you echo’d the url and then copy/pasted it to try and make sure the url is a valid one? If it is, it’s probably something to do with the way you are trying to redirect. Where are you echo’ing top.location.href to? Is that in your as a refresh?
This happened to me as well. I was copy/pasting from the tutorial, and it turned out some of the single quotes need to be fixed when you copy/paste, they were the wrong utf type (or whatever you say). So type the single quotes over top the pasted ones and you should be good.
Back again. This is about as far as I could get- it works, but has certain issues stated below. Maybe someone could expand on this, or provide a better solution.
api(“/YourID/tagged”);
$maxitem =10;
$count = 0;
foreach($photos[‘data’] as $photo) {
if ($photo[‘type’] == “photo”):
echo “”, “”;
endif;
$count+= 1;
if ($count >= “$maxitem”) break;
}
?>
Issues with this:
1) The fact that I don’t know a method for graph querying specific “types” of Tags, I had to run a conditional statement to display photos.
2) You cannot effectively use the “?limit=#” with this, because as I said the “tagged” query contains all types (photo, video, and status). So if you are going for a photo gallery and wish to avoid running an entire query by using ?limit, you will lose images.
3) The only content that shows up in the “tagged” query is from people that are not Admins of the page. This isn’t the end of the world, but I don’t understand why Facebook wouldn’t allow yourself to be shown in this data as long as you posted it “as yourself” and not as the page.
Joe, I don’t have much experience with FQL but maybe you can do what you need with it. Check out this documentation page: http://developers.facebook.com/docs/reference/fql/photo_tag/ and good luck. Let me know if it works.
require_once ‘config.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 “”, “”;
}
}
i Used to the above code to view the albums but nothing is displayed..Should i must change any things in this code. Pls help me.
Are you getting any error messages? Did you already create an app and update all the information? Can you try to turn on php errors on to see what is failing?
Great tutorial! My question is how do I get my friend’s statuses? Your “get status post” works great for my statuses but how do I get a friends? Thanks!
Hey Randy, I assume you need to add the extended permissions to access that information and then you should be able to get it using your friends id.
Joey,
Thank you so much for taking time and helping all of us fellow developers here.
I m trying your on facebook canvas (the place where we use/operate fb applications. My problem is, it always shows there’s no session going on and there is no user logged in, which is not the case. Anything you can suggest? I m using the code from the tutorial above. Any advice will be helpful
Cheers,
I don’t have any experience with canvas but it seems many here have issues using this code and canvas. I’ll have to try it out to see where the problem is.
Thank you so much for this tutorial. It helped me get exactly what I wanted… displaying albums and photos. This was the first place that I found this information after searching for hours. Thanks a lot!
Hi
I am stuck in problem and not getting any solution
I want to update facebook user profile basic information like (hometown, about, date of birth etc…),
I am getting user information with this code
$fql = “select name from user where uid = me()”;
$status1 = $facebook->api(array(‘method’ => ‘fql.query’,’query’ =>$fql));
but now i want to update name of this user using any fb method or fb php api
i just tried this method for update
$fqlupd = “update user set name = ‘Saad Yousaf Updated’ where uid = me()”; $status1 = $facebook->api(array(‘method’ => ‘fql.query’,’query’ =>$fqlupd));
but fql query showing error on update query.
kindly tell me any other solution.
I am using facebook php API
I am waiting for reply
Regard
saad
Hi Saad, I haven’t used FQL but maybe someone here can answer that question for you.
hello, i am creating a website and i would like users to be able to post notes to a facebook page using :
http://developers.facebook.com/docs/reference/api/note/
i am confused as to how to do this using the example you have given above.
i currently have a page on my site with a form with textarea for subject and message. how do i make what users type in this text area appear as a note on faceboook???
help greatly appreciated
Nelle, adding a note should work like the add new status example just using the notes url instead of feed at the end.
Great article! Thanks you
Hi Joey,
For starters, very nice job you’re doing. Really helpful. 🙂
I have a problem. Is there a way to customize the “via [ApplicationName]” at the bottom of the post? I’ve seen a post on my wall that does this.
Thanks!
I haven’t tried to do this. In the list of post options, there is one called attribution which says “A string indicating which application was used to create this post.” It may only be a read-only value, but you can try passing that property when doing a post and see if Facebook accepts it. Ex:
array(‘message’ => ‘This post came from my app.’, ‘attribution’ => ‘SampleApp’));
I would like to know how to use paging. When you use limit in the api call, you get a paging array with navigation. How do I use this to update the php call?
Honestly I haven’t tried paging yet. I would have assumed you get the data in the same format.
Helped me a lot man,thanks
Waaaay better than the documentation at facebook.com
Keep up with the good work =)
I am trying to read all the status messages on the user using facebook->api(/me/statuses but it only returns 25 status messages. I also tried the /me/posts with the same result. Can you help me on this??
Hi, try the paging information in the following page: http://developers.facebook.com/docs/reference/api/
Paging
When querying connections, there are several useful parameters that enable you to filter and page through connection data:
limit, offset: https://graph.facebook.com/me/likes?limit=3
until, since (a unix timestamp or any date accepted by strtotime): https://graph.facebook.com/search?until=yesterday&q=orange
If you use those parameters, you should be able to retrieve all the information you need.
Hola, gracias por el tutorial, esto de traer fotos de facebook a mi website es justo lo que he estado desde hace varios dias buscando. el codigo me resulto a la perfeccion ;). Solo tengo una pequeña consulta o dua: el codigo me trae solo 25 fotos de cada album que poseo en facebook, ¿esto es por defecto o es parametrizable en alguna linea o solo a mi me pasa?
Thanks for all!
Hola, trata la informacion en esta pagina: http://developers.facebook.com/docs/reference/api/
Paging
When querying connections, there are several useful parameters that enable you to filter and page through connection data:
limit, offset: https://graph.facebook.com/me/likes?limit=3
until, since (a unix timestamp or any date accepted by strtotime): https://graph.facebook.com/search?until=yesterday&q=orange
Deberias poder pasar estos parameters limit y offset para resolver tu problema.
Solucionado!, Gracias de nuevo, solo agregue ?limit=X y listo.
$limit_picture=80
try{
$photos = $facebook->api(“/$abm/photos?limit=$limit_picture”);
}
catch(Exception $o){
print_r($o);
}
foreach($photos[‘data’] as $photo)
{echo $i.” – “; $i++;}
Lovely Guide… I easily started my first application and learning quickly. Thanks!
My contribution for Profile Pictures FQL.
$pics_fql= “SELECT aid,type FROM album WHERE owner =”.$user;
$pics= $facebook->api(array(‘method’ => ‘fql.query’,’query’ =>$pics_fql));
$p_id= $pics[0][‘aid’];
$p_id_fql= “SELECT owner,src_small,src_small_height,src_small_width,src_big,src_big_height,src_big_width,src,src_height,src_width,link,caption,created,modified,object_id FROM photo WHERE aid='”.$p_id.”‘”;
$albums= $facebook->api(array(‘method’ => ‘fql.query’,’query’ =>$p_id_fql));
foreach($albums as $album)
{
$pic_src=$album[‘src’];
echo “”;
}
Thanks for that. That helps me understand better FQL as I still haven’t played with it.
Thanks a lot for this tutorial;
but if such a scenario arises where the user has authorized the application
but revokes the permission of say just the publishing rights later – it would lead to an ‘Uncaught OAuth exception’.Is there a way to avoid that?
That’s an interesting scenario. I assumed a user could only remove the app but not individual permission settings. I’d have to research this one, maybe there is a way to check for each permission before assuming it’s a valid session.
Do you know if there is some way to get a list of applications for a user? I am trying to create tabs from my application – but it seems like I have to create a new app for every page and I can’t seem to find out how to get information about created apps without knowing the app id first.
I do not, but if you find out please do let me know as I had the same issue.
great post joey.
i have one question…
when i post a status update i want facebook to embed the link to display the image. i’ve tried using ‘picture’ but the error message reads ‘FBCDN image is not allowed in stream’
i have permission to the; user_status, publish_stream and read_stream
any ideas would be much appreciated
thanks.
Ah nevermind that i understand the error message now. facebook doesn’t want to post images that are hosted on the facebook database. im sure you could have told me this.
anyway thanks for the awesome tutorial!
That is correct, facebook doesn’t allow you to stream their pics. What I had to do is first download the image in my local server and use a link that points to that new copy of the image.
Hi, really nice library.
I’ve made my app, but I want to auto login myself instead of authenticating everytime.
Could you give me detailed instructions, as to what I can do in the existing script to autologin.
Thanks alot
Hey Akshay, what do you mean by autologin? I’m not sure I follow.
hi Joey,
please help regarding uploading photo using jquery/ajax method;
d script:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
$facebook->setFileUploadSupport(true);
$attachement = array(‘access_token’ => $session[‘access_token’],
‘source’ =>’@’ . realpath($lnk),
‘name’ => ‘my random friend’,
‘message’ => ‘m pic;get yours at http://apps.facebook.com//‘
);
$fb_photo = $facebook->api(‘me/photos’,’POST’,$attachement);
dump of response error :::::::::::::::::::::::::::::::::::::::::::::::::::
curlException occuring:
[message:protected] => failed creating formpost data
[string:private] =>
[code:protected] => 26
[line:protected] => 639
[trace:private] => Array
(
[0] => Array
(
[file] => /home/*******/public_html/******/facebook.php
[line] => 592
[function] => makeRequest
[class] => Facebook
[type] => ->
[args] => Array
(
[0] => https://graph.facebook.com/me/photos
[1] => Array
(…..
please help regarding this;;it will be great;;
Unfortunately I don’t see anything wrong with this code. I found a little information in Google about this issue and I hope it helps you: http://stackoverflow.com/questions/2964410/how-can-i-upload-photos-to-album-using-facebook-graph-api. I assume the $lnk var is pointing to a valid file and I don’t remember if having a ‘/’ before me mattered or not – but try it out. /me/photos vs me/photos.
I have a need to do an event via the API and I am having issues with getting it to post. I need the event to post to a fan page that I am the admin of how do I do this any help would be REALLY Appreciate as this is driving me crazy.
Jeremie,
You should be able to do something like api(‘/me/events/’, ‘POST’, array(‘name’ => ‘This is my event’, ‘start_time’ => ‘the start time’));
The only tricky part here is that you have to use the required format for start time which is from their docs: ISO-8601 formatted date/time or a UNIX timestamp. More info at http://en.wikipedia.org/wiki/ISO_8601. Hopefully this helps.
Joey
Hi Joey,
Just want to know, is there is any way I can upload images from my local hard ?… I was trying to send $var to $img = realpath(“$var”); like that but didn’t work 🙁 why is that so? Please help me.
thanks
The example in this post is uploading a picture from the hard drive so it should work. What error are you getting?
Hi, thanks for the tutorial.
I downloaded your files and edited the config.php with my datas.
When I open your app facebook asks me to login, then facebook redirects me to my profile page … can you exlpain me why?
Thanks in advance … I have to do a university project about facebook and I really need to understand the php sdk 🙂
I’m not sure why it would take you back to your profile. It should take you back to the app that originated the authorization call – assuming that’s the same url you used when you setup your facebook app account. Is this the case?
Hi Joey,
Great article. I’m debating whether to use the PHP SDK to call Graph APIs… can’t we achieve the same by using CURL in our own library which gives us more control? This way, we can send batch requests:
$mch = curl_multi_init();
$ch1 = curl_init($url1);
$ch2 = curl_init($url2);
curl_multi_add_handle($mch, $ch1);
curl_multi_add_handle($mch, $ch2);
do {
$mch = curl_multi_exec($this->_mch, $active);
} while ( $mch === CURLM_CALL_MULTI_PERFORM );
Do you like the PHP SDK and is there a benefit to using it instead of writing our own?
Hey Brandon, I’m glad you enjoyed the article. The Facebook PHP SDK actually does use curl the same way you would. It simply adds an extra layer of methods to facilitate the use of the api without having to dig too much into the details. I personally like and use it – and have been using it for the last couple Facebook projects I worked on. For the last two I ended up creating a new class that extends the facebook class to add some extra functionality while still allowing me to update the facebook library when there is an update. In the end though, it’s up to personal preference and the whole reinventing the wheel thing.
Great write up, unfortunately I can’t get it to work. I tried running index.php from the download package and clicking on “Friends”, “view list” and got this error:
Fatal error: Uncaught OAuthException: Error validating access token: The session has been invalidated because the user has changed the password or because auth.expireSession was called. thrown in /home/content/66/6289466/html/fb_examples/library/facebook.php on line 543
Any ideas?
Did you get the facebook login/authorization screen first? I think I got that error once and had to clear cookies in my browser cause my session was all messed up. Try and see if that helps.
I can not thank you again. I had literally been pulling my hair out trying to find a way to break the ice with the PHP SDK and the graph API. Amazingly poor documentation out there! Your page has helped a lot.
Hello Joey tnkx for ur great tutorial!!!!Its really very helpful to learn basics for beginners. And am creating canvas application where i wann to list top three persons who viewed my profile(Current user who logged in) most?If u have any idea pls do help me..
Ashok, I’m not sure if this information would be available to you from Facebook. If someone knows, maybe they’ll chip in here. If not, the other solution I could see would be to track user activity in a database on your end. Each time a user accesses your app, you store their user id in a db table.
master, cant do anything, the facebook sdk version changes at all times. On what version did you based this tutorial ?
You need to edit this tutorial to append the sdk version number.
That’s a good point, I should add the version. I’m looking through the Facebook doc (http://developers.facebook.com/docs/reference/api/) and don’t see any version information though. Do you know where I could find this? What part of this tutorial isn’t working though, as far as I can tell, the code shouldn’t have changed.
I am new to facebook API. This blog is one of the best blogs exist on the web for facebook API.
I need to know the code to show pictures(Thumbnails) of my fan page. I need to display these pictures on my site. What would be the code to do that? Is there any $facebook->api(‘/me/fanpage’ exist? I have used this method
$facebook_album = file_get_contents(“http://www.facebook.com/pages/Imrans-Fan-Page/165946010093388”); to get the data but it asks me for login.
Thanks in advance.
Hey Khan,
Take a look at the page_fan documentation using FQL. It might have what you are looking for: http://developers.facebook.com/docs/reference/fql/page_fan/
Hi,thank you for the tutorial, it really helped me. But i what im trying to do, is set a infinite session for my server that will be posting regularly and when i try to call $facebook->getSession(); or $facebook->setSession(); it says: “Fatal error: Call to undefined method Facebook::getSession() in…” i think that method have been removed, am i right? How can i do the same thing with the latest version?
Thank you!
Interesting, you are correct and the PHP SDK has changed. They have now created an abstract base class which can be extended to define how you want to store your access token. I’m glad they did it this way since we usually ended up having to extend it anyways. Just from looking over the code, it seems you can open the facebook class and modify the get/setPersistentData methods to store and load that token in a location of your choice such as a database. Both methods are automatically called from the base class during __construct or when authenticating. Try it out and let us know how it goes.
Joey, first, this is an amazing tutorial, is extremely well written and has solved a problem I have been trying to get past for about a week. My hats off to you. If you have a paypal link, throw it in here…this is information worth paying for 🙂
As for my question: I have two facebook accounts. Is it possible to post to both walls at the same time? I already authorized both accounts by running config.php a second time (when I was logged into my second account), but trial and error has not enabled me to figure out posting to both walls simultaneously.
Any suggestions? I’d be extremely grateful (and yes, such an answer is 100% paypal worthy to me…!)
— Jer
Jer, I’m glad you found this to be helpful. I put this up to share with others but if you insist on a paypal link I’ll send you an email 🙂 About your questions, I can think of a one thing to try. First, request offline access permission with both accounts when authenticating and then store your access tokens in a db after authenticating. I know with the older PHP SDK you would call get/setSession but with the new SDK it’s a bit different. When you want to post to both walls, load up the first token, instantiate the facebook class with that token, post to the wall, unset that facebook instance, then load up the second token, and post to that wall. Let me know if that works.
Very nice article. Helped me understand a lot.
Am trying to make a application that will post to the users wall one wallpaper every week. What is the method to post to all the users of application? This article did make it clear how to post to the current user. Thanks
Safwan, I’m glad you found this article informative. As far as your question, check the comment above that I left for Jer. It’s one way to do what you want although there may be more efficient ways out there.
Hello. thanks for this article, really informative and got me starting on app building. I need some help on building mine though, I’m making an app and this app will save some information from the user to the app so that other users of the app wuld be able to see that info. It’s ok since it’s an app exclusively for a group.
What’s the way to do this, should I save it to a sql database for retrieval and how do i make it so that it will change everytime the person changes his/her info. Basically how will i be able to access the info of someone not currently using the app.
Hey, I’m not sure I completely understand your question. You want to track users who access your app so in that case you would want to store some information in a db. You can track as much information as they allow depending on the permissions they agreed to when first authenticating to your app. Now, if you requested offline permission, I assume you could every once in a while, using their stored token, call their fb profile to see if any information has changed to update your db? Just a thought…
I see so it’s offline permissions. Seems like i don’t know enough php to understand how it works with tokens and stuff.
Awesome article, Thx. I am having a problem with the new PHP SDK. As someone mentioned Facebook removed getSession(). I was wondering how can I check if the user is the session? (assume the user is connected to my website previously. He accepted my permissions and everything.) In the previous SDK(RESt) I could get if getSession(), do … else show the login dialog. how can I do this with the new graph API? I have subclassed the API and this is my method, but doest work:
public function getSession(){
$old_rest_call_param = array(
‘method’ => ‘auth.getsession’,
‘auth_token’=> $this->FB->getAccessToken()
);
return $this->FB->api($old_rest_call_param);
}
Apoo,
Unfortunately I haven’t played with the latest version of the SDK so I can’t comment. Maybe someone else has had a chance and can comment.
Joey
Hi joey, i followed you’re tutorial but it seems that when i try to get the request permission for my app the loads blank. Any ideas? pls help
It could be that an error it happening but you may have errors turned off on your server so you can’t see them. Can you make sure error you have errors turned on and showing everything (http://php.net/manual/en/errorfunc.configuration.php)? Or check your logs as well for information there.
FYI: “req_perms” is now “scope” for the permissions request…
Also “canvas” and “fbconnect” might be useless in getLoginUrl() according to someone on IRC.
I’m going to have to update this at some point as it seems lots has changed with the PHP SDK and/or the Graph API.
I also need this app to be able to post when I am not logged in AND would like to post an identical message (I’m online now) each time. I get a duplicate message error now – is there a workaround for that?
As far as I know, you can’t post the same identical message twice, you would have to change something in it like add a period. To post when you are not logged in, you need to first request offline permission when you authenticate. After you authenticate, you need to store that session token into a file or database and each time you make a request to the Api you’ll have to send that token with it. Hope this helps.
The duplicate message I get is this:
“(#100) The status you are trying to publish is a duplicate of, or too similar to, one that we recently posted to Twitter”
Is that from your code? I ask because it says “Twitter”?
Small changes in the text to post do not work, so I’ll have to rotate between different phrases….
I have already done the “manage_pages” permission by adding that to the config file and will add offline_access now.
You are correct, that was Twitter that enforces that restriction and not Facebook. I had that same problem when I was doing some tests and passing the same message but then I started adding some random bits to make it work until my tests were done.
Hi There,
Can you please tell me why i am getting this error
Fatal error: Uncaught OAuthException: (#200) The user hasn’t authorized the application to perform this action thrown in /library/facebook/base_facebook.php on line 1033
: |
Unfortunately I’m not sure. At some point I was getting some authentication issues and clearing my cache and forcing a session reset in the facebook account by deleting the user logging into the app fixed my problem. Try that.
Hi Joey, awesome article !!
My goal is to create an event AND to invite friends… creating an event is not that difficult, but I don’t seem to find information on how one can invite friends ?
hey Johan,
It seems the only way atm to do this is to use the old REST api. You can still call these older methods using the PHP Facebook SDK. Here is an example: http://stackoverflow.com/questions/3346634/how-to-invite-a-users-friends-to-an-event-facebook-graph-api
Hope this helps.
Hi,
I am not able to post my message when i am not logged in. Everything is configured propert, i got offline_access also, but this codes does not work when i am not logged into facebook. It got the facebook login page when i execute this page. If i am logged in then it is working fine. Can you please help me to resolve this.
‘app id’,
‘secret’ => ‘secret key’
));
$session = $facebook->getSession();
if(!empty($session))
{
# Active session, let’s try getting the user id (getUser()) and user info (api->(‘/me’))
try
{
$uid = $facebook->getUser();
$user = $facebook->api(‘/me/accounts’);
}
catch (Exception $e)
{
echo “error “. $e;
}
if(!empty($user))
{
# User info ok? Let’s print it (Here we will be adding the login and registering routines)
print_r($user);
foreach($user[‘data’] as $account)
{
if($account[‘id’] == 160603497351263)
{
$access_token = $account[‘access_token’];
echo “Page Access Token: $access_token”;
}
}
$uid = $facebook->getUser();
# let’s check if the user has granted access to posting in the wall
$api_call = array
(
‘method’ => ‘users.hasAppPermission’,
‘uid’ => $uid,
‘ext_perm’ => ‘publish_stream’
);
$can_post = $facebook->api($api_call);
if($can_post)
{
$attachment = array(‘message’ => ”,
‘access_token’ => $access_token,
‘name’ => ‘test message.’,
‘link’ => ‘http://www.google.com’,
‘picture’ => ”);
# post it!
$facebook->api(‘/160603412341234/feed’, ‘post’, $attachment);
echo ‘Posted!’;
}
else
{
die(‘Permissions required!’);
}
}
else
{
# For testing purposes, if there was an error, let’s kill the script
die(“There was an error.”);
}
}
else
{
# There’s no active session, let’s generate one
$login_url = $facebook->getLoginUrl(array(‘req_perms’ => ’email,user_birthday,status_update,publish_stream,user_photos,user_videos,manage_pages,offline_access’));
header(“Location: “.$login_url);
}
?>
Shaz,
If I remember correctly on my project, I wanted it to always be using the same account no matter who was trying to access it. For this to work I had to request offline_access like you mentioned in your post. Then, I had to modify the getSession and setSession methods in the facebook class to store that session in a db table and get the session from the table. After doing all this, I authenticated once with the correct account (the session was stored and then reused every time) and I was able to get it working without having to be logged in to Facebook through that browser.
help me.
how post content to note or fanpage Using facebook APi
thank you.
Jubpas, unfortunately I haven’t tried these. Maybe someone here has some insight.
How to debug anything while developing facebook apps. MY screen is always empty white …i Cant see anything. But i can see echo “test” if i write on top of my file.
There are a couple things to try. You may have your error reporting turned off or errors not displaying. Here is more info on error_reporting and display_errors: http://docs.php.net/manual/en/errorfunc.configuration.php#ini.error-reporting. The other thing you can do is check your php error log file since that should have any errors and warnings encountered. Do a phpinfo() to see where that log is stored and open it to look.
OMG… Really An Awesome Tutorial… I Tried Too Many Tutorials… But No One Was Perfect… But You Are Awesome 🙂 Thanks a Lot…
Glad you found it helpful.
Any chance you know how to upload a profile cover to the new timeline?
Hey Bobby, I do not but maybe someone here might.
I am developing one facebook application.I have album details .In which I got cover photo Id. I want to show the cover photo how can show the cover photo from this cover photo Id.
Also I have photo array from the particular photo album . I used source and picture to show this photos from album .But after selecting photos I saved photo Id and in next page I want again source of photo from this photo Id.
Can you please help me for this.
So if you have the link to show the album details, you can add picture at the end of the url to use the picture connection which:
If you have the cover photo id (picture id of the albums cover photo) only, you should be able to call the photo object using that id and then get the url in the picture property. Hope this helps.
Hello ,
I am using below code
require_once ‘config.php’;
// get albums
$albums = $facebook->api(‘/me/albums’);
foreach($albums[‘data’] as $album)
{
$intAlbumId = $album[‘id’];
$coverphotoid = $album[‘cover_photo’];
$fql = “select src_big from photo where pid =’$coverphotoid'”;
$ret_obj = $facebook->api(array(
‘method’ => ‘fql.query’,
‘query’ => $fql,
));
print_r($ret_obj);
}
But print_r($ret_obj); is giving me blank array.
Puja, try going to the Graph API explorer tool to see if you get results. The link is: http://developers.facebook.com/tools/explorer/?method=GET&path=me%2Falbums
Click on “get access token” and select user_photos as that is the permission you need to view albums. Then click on “submit” and see if anything comes back. If you are getting data back from facebook, I would look at your php error logs to see if there are any errors when running your code.
Hi,
i am having an application. i tried to access the albums in my account with the application but its returning an empty array.
i tried the url directly in the browser..
the url used is
https://graph.facebook.com/me/albums?method=get
&access_token=…
looking forward for reply
Avantika, try going to the Graph API explorer tool to see if you get results. The link is: http://developers.facebook.com/tools/explorer/?method=GET&path=me%2Falbums
Click on “get access token” and select user_photos as that is the permission you need to view albums. Then click on “submit” and see if anything comes back. If you are getting data back from facebook, I would look at your php error logs to see if there are any errors when running your code.
Joey question Im trying to implement facebook in my site where users can grab photos from there albums and upload them to my site. Im having a hard time doing all this. Any chance you can help me. Iv been reading the developers site on facebook but cant seem to understand the part about pulling the data. I can get them to allow pop up but after how do i pull the info. Im more of a php guy.
Hey mik, I’m not sure I understand exactly what you are asking. If you want users to browse their photos, select a photo, and upload it to your server then what you can do is pass the photo url to your server and have it do a file_get_contents to download the file. Check my response to Puja’s comment, sounds like the same thing you are trying to do.
Thanks …I got the cover photo Using FQL queries.
Now I want to copy facebook album photos to my local machine.I have source of the photos. Can I do this?
Thanks in advance.
If you have the url to the photo, you can do something like
$data = file_get_contents($photo_url); // get the data from the url
file_put_contents(‘image.jpg’, $data); // store the data as an image file on your system
Thanks Joey .I will try this.
Hola, tengo un inconveniente con tu ejemplo ojala me puedas ayudar:
El código para publicar en el muro es el siguiente:
function publicarMuro(){
// add a status message
//alert(msg);
api(‘/me/photos’, ‘POST’,
array(
‘source’ => $img,
‘message’ => ‘Esta foto viene desde mi app.’
)
);
var_dump($photo);
?>
Pero no funciona, lo raro es que el postear solo texto si funciona, he intentado poniendole:
// allow uploads
//$facebook->setFileUploadSupport(“http://” . $_SERVER[‘SERVER_NAME’]);
pero da igual.
Gracias por tu ayuda
Sebastian,
Aqui tengo un ejemplo: https://github.com/joeyrivera/Facebook-Graph-API-Examples/blob/master/photos_add.php
Si tienes una nueva version del api pasa true para setFileUploadSupport. Tambien no te olvides del ‘@’ antes del $img variable.
Alright I’ve looked all over for how to post an update as a page to the page. I’ve seen how you can update a App Profile, but not the page itself. How would I go about doing that?
Also, I keep getting this error when running this (using codeigniter, hence how I’m loading the library):
$config = array(‘appId’=>’NONEYA’,’secret’=>”NONEYA”,’cookie’=>true);
$this->load->library(‘facebook/facebook’,$config);
$me = $this->facebook->api(‘/me’);
print_r($me);
“Fatal error: Uncaught OAuthException: An active access token must be used to query information about the current user.”
Yes, I’m logged in, I’m an admin of the app and page.
best sample php-facebook so far
now i see real sample and want to do it
other site just show technical howto
keep it up 🙂
Hey there Joey, I’m wondering if you’ve found any way to retrieve events posted by the application?
The events created by the app display as being created by user and app, but when I query creator/owner all I get is the userID. I tried with FB.api(‘/168592903230706/events’) but I get nothing. Am I looking in the wrong place?
Also tried with FQL, it works with userID but not with applicationID
‘SELECT eid, name, start_time, creator FROM event WHERE eid IN (SELECT eid FROM event_member WHERE uid = me()/*or APPID*/)’
From the graph explorer I can see albums, images, status from my App Profile Page, but no events even thou I’ve created 10+ (http://developers.facebook.com/tools/explorer/?method=GET&path=168592903230706)
(You probably can’t see my app because it’s in sandbox mode, but you can see if there are any event objcts in an app)
…You just saved me from nights of trying to figure this out!! Awesome. This is extremely useful!!
Hey joeyrivera , thank you for post … its really working in my case… thank u .. very much ..
hi.. i am searching for a sample code on curl php that can display pictures found in a public album of a friend.
can anyone help please?
thanks
Hey, I need to solve a problem to my client, that i need to do a crontab, he post an article and each 30 minutes have a file that verify if my database in notices table have a post with the column facebook = ‘S’, if have public this article on his facebook, but i need to find a way that the user dont need to log in everytime he post something, so i enable the offline_acess and try to get the inifite session key, but when i use the function “$facebook->api_client->auth_getSession($auth_token);” the PHP return a error = “Fatal error: Call to a member function auth_getSession()”, and i dont know why it appear, because i found a lot of tutorials asking to use this function and everytime return this error.
Could you save me about it?
I’m using the last version of SDK-PHP
The SDK has changed since I first wrote this post, you’ll have to see what the newer methods are to store and get the token in your SDK – it should still work in a similar fashion though. Authenticate, store the token, and reuse it every call.
Hey Joey, I was wondering if there was any quick and easy way to grab the number of likes a fan page has and use them throughout the site using an echo function?
I want to delete the photo from facebook using Graph API.But i am getting error as—Fatal error: Uncaught OAuthException: (#3) Application does not have the capability to make this API call. thrown in C:\wamp\www\FacebookApp\facebook-php-sdk-6c82b3f\ src\base_facebook.php on line 1106
This has been reported as a bug on https://developers.facebook.com/bugs/125524667559003?browse=search_4f14be86ba58f3666689319
Can I Delete a Album using Graph API in PHP?
Type your comment here
Thanks alot,
millions of thanks…………..
🙂
Awesome article! Just what I was looking for to add fb to mssg.it
Hello. Thanks for sharing it is very well organized and understandable. I just wanna ask if it is possible to set the user id?? or to authenticate using the user_id and not using the appID and secret?? The user ID is stored in my site’s database. I want to do this because when I’m logged out of facebook, it doesn’t post the status that I’ve set on my site.
The user id is not enough to authenticate as it’s public information. In order for your application to post a status to a user, the user must be authenticated through your application. Now, you can use the offline permissions option so they only authenticate once and you can store the authenticated key in the db and use that to post status updates anytime after.
great tutorial very useful and helpful.
wow, this is a great page and I have to say, most of the great stuff is in the comments 🙂
you should formalise some of the information and rewrite a new article based on all the new info you accumulated there, cause it’s pure gold!
There seems to be a problem with config.php file.Rather than using
if(is_null($facebook->getUser()))…
to check if user is present I use following code for checking if user already exists
try{
$me = $facebook->api(‘/me’);
$error=’no’;
}
catch (FacebookApiException $e) {
$error=’yes’;
$perms=array(‘req_perms’ => ‘user_status,publish_stream,user_photos,email,status_update,friends_status,export_stream’);
echo”getLoginUrl($perms,$cancel,$next,$display).”‘>”;
exit;
}
if($error!=’yes’){//already logged in use normally
}
hi..joey..i am trying to extract friends likes…but i am getting an error
! ) Fatal error: Uncaught OAuthException: Unknown path components: /friends_likes thrown
how to resolve this?
Hey Vac, where do you see friends_likes? I assume you’d want to try something like: graph.facebook.com/[friend name or id]/likes.
ex:
https://graph.facebook.com/cocacola/likes
Hello Joey
I tried to create the small application for extracting the data from facebook and I receive the following error in the error.log file:
[Wed Nov 07 17:21:46 2012] [error] [client 127.0.0.1] PHP Fatal error: Uncaught CurlException: 1: Protocol https not supported or disabled in libcurl\n thrown in /srv/www/htdocs/base_facebook.php on line 967
Any idea?
Thanks
Paulo
Seems like you don’t have https support in php. Here is a link that may help: http://stackoverflow.com/questions/10664126/https-with-php-curl-protocol-not-supported-but-curl-command-line-connects-fin
Hello Joey
Nice tutorial… Can you provide me the code of downloading all the photos from facebook profile through facebook php sdk
Great article! Just what I have been looking for, for ages! Sadly, it isin’t updated to 2013, and most of it doesn’t work.
Is there anything else similar to this, or would it be possible for you, Joey, to update it to 2013? Would be great!
Again, good job! Please let me know, whether anybody knows a similar updated article.
thanks joey ! 非常不错,很有用的代码。。