In this article I’m focusing facebook latest php sdk to integrate facebook features in your site. Some days ago facebook released their new graph api system and updated their core structure. They also officially released php sdk so that you can easily call facebook latest graph api and old legacy api from server side by php.
Before proceeding first have a look my previous article specially Facebook connect authentication part.
In this post I’ll show
- How to check valid session of user, if user successfully logged in
- How to call graph api
- How to call legacy api
- How to update status dynamically using graph api
- How to use FQL Query
So take a look my demo of this tutorial. Please login by FBConnect and approve all the permission if you’re first time accessing the page.
Updated Tutorial
Follow this post based on PHP SDK 3.0 by Facebook and skip current post.
STEP 1:
First download the php sdk libary from here . Now copy the facebook.php from /src/ to your project dir.
STEP 2:
Create a file named fbmain.php. And copy below code to this file.
<?php
$fbconfig['appid' ] = "your application id";
$fbconfig['api' ] = "your application api key";
$fbconfig['secret'] = "your application secret key";
try{
include_once "facebook.php";
}
catch(Exception $o){
echo '<pre>';
print_r($o);
echo '</pre>';
}
// Create our Application instance.
$facebook = new Facebook(array(
'appId' => $fbconfig['appid'],
'secret' => $fbconfig['secret'],
'cookie' => true,
));
// We may or may not have this data based on a $_GET or $_COOKIE based session.
// If we get a session here, it means we found a correctly signed session using
// the Application Secret only Facebook and the Application know. We dont know
// if it is still valid until we make an API call using the session. A session
// can become invalid if it has already expired (should not be getting the
// session back in this case) or if the user logged out of Facebook.
$session = $facebook->getSession();
$fbme = null;
// Session based graph API call.
if ($session) {
try {
$uid = $facebook->getUser();
$fbme = $facebook->api('/me');
} catch (FacebookApiException $e) {
d($e);
}
}
function d($d){
echo '<pre>';
print_r($d);
echo '</pre>';
}
?>
First update $fbconfig array by your application’s id, api key and secret key. In the code you’ll see I included facebook.php by include_once. If your server has no curl extension and json extension, you’ll see error message. Until you don’t install curl and json extension this sdk will not work.
$session = $facebook->getSession();
This method returns session information of user. It may be empty if user yet not logged in your site or user’s session is invalid. To check user’s session validity you’ve to first call an api, if user’s session is valid then the api will return result.
So if $fbme is not null that means user successfully logged in via facebook and user’s session is valid. So before calling any api use conditional logic like if ($fbme) { then call api}.
I also defined a method named d() to dump data quickly.
STEP 3:
Now create another file named index.php and copy below code and checkout my description at the end.
<?php
include_once "fbmain.php";
$config['baseurl'] = "http://thinkdiff.net/demo/newfbconnect1/php/index.php";
//if user is logged in and session is valid.
if ($fbme){
//Retriving movies those are user like using graph api
try{
$movies = $facebook->api('/me/movies');
}
catch(Exception $o){
d($o);
}
//Calling users.getinfo legacy api call example
try{
$param = array(
'method' => 'users.getinfo',
'uids' => $fbme['id'],
'fields' => 'name,current_location,profile_url',
'callback'=> ''
);
$userInfo = $facebook->api($param);
}
catch(Exception $o){
d($o);
}
//update user's status using graph api
if (isset($_POST['tt'])){
try {
$statusUpdate = $facebook->api('/me/feed', 'post', array('message'=> $_POST['tt'], 'cb' => ''));
} catch (FacebookApiException $e) {
d($e);
}
}
//fql query example using legacy method call and passing parameter
try{
//get user id
$uid = $facebook->getUser();
//or you can use $uid = $fbme['id'];
$fql = "select name, hometown_location, sex, pic_square from user where uid=" . $uid;
$param = array(
'method' => 'fql.query',
'query' => $fql,
'callback' => ''
);
$fqlResult = $facebook->api($param);
}
catch(Exception $o){
d($o);
}
}
?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:fb="http://www.facebook.com/2008/fbml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<title>PHP SDK & Graph API base FBConnect Tutorial | Thinkdiff.net</title>
</head>
<body>
<div id="fb-root"></div>
<script type="text/javascript">
window.fbAsyncInit = function() {
FB.init({appId: '<?=$fbconfig['appid' ]?>', status: true, cookie: true, xfbml: true});
/* All the events registered */
FB.Event.subscribe('auth.login', function(response) {
// do something with response
login();
});
FB.Event.subscribe('auth.logout', function(response) {
// do something with response
logout();
});
};
(function() {
var e = document.createElement('script');
e.type = 'text/javascript';
e.src = document.location.protocol +
'//connect.facebook.net/en_US/all.js';
e.async = true;
document.getElementById('fb-root').appendChild(e);
}());
function login(){
document.location.href = "<?=$config['baseurl']?>";
}
function logout(){
document.location.href = "<?=$config['baseurl']?>";
}
</script>
<style type="text/css">
.box{
margin: 5px;
border: 1px solid #60729b;
padding: 5px;
width: 500px;
height: 200px;
overflow:auto;
background-color: #e6ebf8;
}
</style>
<h3>PHP SDK & Graph API base FBConnect Tutorial | Thinkdiff.net</h3>
<?php if (!$fbme) { ?>
You've to login using FB Login Button to see api calling result.
<?php } ?>
<p>
<fb:login-button autologoutlink="true" perms="email,user_birthday,status_update,publish_stream"></fb:login-button>
</p>
<!-- all time check if user session is valid or not -->
<?php if ($fbme){ ?>
<table border="0" cellspacing="3" cellpadding="3">
<tr>
<td>
<!-- Data retrived from user profile are shown here -->
<div class="box">
<b>User Information using Graph API</b>
<?php d($fbme); ?>
</div>
</td>
<td>
<div class="box">
<b>User likes these movies | using graph api</b>
<?php d($movies); ?>
</div>
</td>
</tr>
<tr>
<td>
<div class="box">
<b>User Information by Calling Legacy API method "users.getinfo"</b>
<?php d($userInfo); ?>
</div>
</td>
<td>
<div class="box">
<b>FQL Query Example by calling Legacy API method "fql.query"</b>
<?php d($fqlResult); ?>
</div>
</td>
</tr>
</table>
<div class="box">
<form name="" action="<?=$config['baseurl']?>" method="post">
<label for="tt">Status update using Graph API</label>
<br />
<textarea id="tt" name="tt" cols="50" rows="5">Write your status here and click 'submit'</textarea>
<br />
<input type="submit" value="Update My Status" />
</form>
<?php if (isset($statusUpdate)) { ?>
<br />
<b style="color: red">Status Updated Successfully! Status id is <?=$statusUpdate['id']?></b>
<?php } ?>
</div>
<?php } ?>
</body>
</html>
The code is very easy to understand. First part contains php logic, api call and collection of data. Next part is html/javascript to view data (javascript for fbconnect authentication).
Please change
$config['baseurl'] = "http://thinkdiff.net/demo/newfbconnect1/php/index.php";
And set baseurl to your project url. And never forget to set your facebook application Connect URL. It would be your project url.
In index.php I used javascript based fbconnect authentication and fbml tag to show login button and logout button. If you don’t want to use javascript for this purpose, you can generate login/logout links using php code.
Generate login/logout button using this php code
// login or logout url will be needed depending on current user state.
if ($fbme) {
$logoutUrl = $facebook->getLogoutUrl();
} else {
$loginUrl = $facebook->getLoginUrl();
}
And show the generated links by below code
<?php if ($fbme) { ?>
<a href="<?=$logoutUrl?>">
<img src="http://static.ak.fbcdn.net/rsrc.php/z2Y31/hash/cxrz4k7j.gif">
</a>
<?php else: ?>
<a href="<?=$loginUrl?>">
<img src="http://static.ak.fbcdn.net/rsrc.php/zB6N8/hash/4li2k73z.gif">
</a>
<?php } ?>
So user will see php generated login and logout button.
In the facebook.php sdk the getLoginUrl() function is defined as
/ * The parameters:
* - next: the url to go to after a successful login
* - cancel_url: the url to go to after the user cancels
* - req_perms: comma separated list of requested extended perms
* - display: can be "page" (default, full page) or "popup"
*
* @param Array $params provide custom parameters */
public function getLoginUrl($params=array()){....}
So if you want that your user approve additional permissions at the first time then generate the url by providing some parameters
$loginUrl = $facebook->getLoginUrl(
array('req_perms' => 'email,read_stream')
);
Now lets discuss more about api calling…
1. How to check valid session of user, if user successfully logged in
I already discussed it in the STEP 1. So I think you already have learned how to check valid session of user. Just remember to use if ($fbme) {call api}
2. How to call graph api
Its very simple. For http://graph.facebook.com/me you’ve to use
$fbme = $facebook->api('/me');
3. How to call legacy api
This is almost same as of graph api calling.
$param = array( 'method' => 'users.getinfo', 'uids' => $fbme['id'], 'fields' => 'name,current_location,profile_url', 'callback' => '' ); $userInfo = $facebook->api($param);
So $facebook->api() is used to call both graph api and old legacy api. If you check the api() method in facebook.php sdk you’ll see
public function api() {
$args = func_get_args();
if (is_array($args[0])) {
return $this->_restserver($args[0]);
} else {
return call_user_func_array(array($this, '_graph'), $args);
}
}
That means if 1st argument is array then the api will call the old restserver.php otherwise it will call the new graph server.
4. How to update status dynamically using graph api
try {
$statusUpdate = $facebook->api('/me/feed', 'post', array('message'=> 'sample status message', 'cb' => ''));
} catch (FacebookApiException $e) {
d($e);
}
in facebook.php you’ll see
function _graph($path, $method='GET', $params=array()) {...}
So the first parameter is for graph path in here https://graph.facebook.com/me/feed, 2nd parameter defines HTTP post or get parameter and 3rd parameter defines array that contains necessary values. So ‘message’ is the message we want as status and ‘cb’ is the callback function which I set to null. Here http://developers.facebook.com/docs/api you’ll see all the information about graph api and their parameters, like
| Method | Description | Arguments |
|---|---|---|
/PROFILE_ID/feed |
write to the given profile’s feed/wall | message, picture, link, name,description |
So to call any graph api just check the manual if you need to pass additional parameters or not.
Another example to retrieve user favorite movie names (https://graph.facebook.com/me/movies) use
$movies = $facebook->api('/me/movies');
5. How to use FQL Query
Currently I don’t find any way to call fql query using graph api. So use the technique of legacy api calling to run fql query
$fql = "select name, hometown_location, sex, pic_square from user where uid=xxxxxxxxxxxxxxx";
$param = array(
'method' => 'fql.query',
'query' => $fql,
'callback' => ''
);
$fqlResult = $facebook->api($param);
I hope this article will help you to understand the usage of php-sdk easily. Demo URL







hi ,
i reading your post and i like it.
i have a lot of trouble with the new graph api, but i found this post.
thx
impressive work again
hi again!
this evening i tested this code . works very well…….always and when this code is hosted out of facebook.
so that i am rewriting the code for that works like a facebook app into a iframe…..
In the road i had issues that i’ll try to solve soon …..when i finish i’ll post here.
greetings!!!
Good job again! What if I would like to develop an FBML application? There is no require_login method in this new SDK!
@Ghido, I yet not tested fbml application. But I think the solution could be, if you don’t find user’s valid session then redirect user to the login url by the following code.
if (!$fbme) { $loginUrl = $facebook->getLoginUrl(); } if (isset($loginUrl)) { header("Location: $loginUrl); exit; }If you test this code let me know if it works or not.
thank you.
Awesome, this simple piece of code solved an issues where IE was not returning a session for a canvan app when the user is already logged in.
Thanks
Is there a way to have a user click a link to update a facebook status and it then prompts them to allow permission? So example:
They come to a site, enter a status in a text area, click “update status”. A pop-up appears and asks them to login if they aren’t already logged into facebook, and then asks for the appropriate permission. If they hit allow, it posts the status.
Is that possible?
Thanks so much for this great tutorial!
I LOVE YOU! Was having trouble figuring it out for a week. Everyday since, I was trying to find better examples. Finally, thanks.
Basically, logging in the user, letting them click “allow” and then posting the status. All with them clicking one button.
I got it figured out! Thanks for the tutorial!
I want to add new authorisation for my application. How to make a new Oauth authorisation request in php please.
Thx
@Ghido is rigth. Before it was posibble to obtain a facebook logued user id with require_login in a fbml application into facebook. Now i cant get that information without requering user relogin again.
@Ghido and @agafex2, if you use iframe base application not fbml you can follow the guideline from facebook.
http://developers.facebook.com/docs/guides/canvas/#canvas
Its very interesting that http://developers.facebook.com/docs/guides/canvas/#canvas in this site only iframe base canvas application discussed.
It seems to me that, facebook will soon deprecate fbml base canvas application development.
@Ghido and others: I think I have found a workaround solution that works for IFrame based application. I have posted that on my blog here: http://bit.ly/cT40vV. Let me know if it works for you!
instead of fql.query it only worked for me with facebook.fql.query
param = array(
‘method’ => ‘fql.query’,
‘query’ => $fql,
‘callback’ => ”
Thank you! This is FAR better than Facebook’s own documentation
Old rest api call aren’t working on the current release of PHP SDK – line 666 is true selecting the read only REST
API which doesnt work – just change it to $name = ‘api’; as a fix!!
theDigitalWarrior
Using the latest php-sdk many people facing problem regarding authentication for fbml/iframe base canvas application. Some of experts suggest me still to use old php sdk library. New php-sdk or new javascript sdk mostly suited for fbconnect base application.
People, if you want to develop iframe base canvas application for facebook, then to know the how to use the authentication system don’t forget to visit http://bit.ly/cT40vV
Thanks to Emran vai for his nice solution there.
Hello. First of all this is a great tutorial thanks so much for it.
Have you been able to successfully authenticate yourself on a subdomain using this code? I have tried but it doesn’t seem to work for me. I have included the base domain in the application settings.
Anyone have any experience with this?
Cheers
rob.
An update for you on this… It does work on sub domains it was the set up of my local development server that was causing the issue.
Cheers
Rob.
Thank you very much for this great tutorial.
you rock! you made an intimidating subject easy to learn. facebook’s documentation is fantastic, BUT there’s too much of it, and no straightforward “start here” tutorial. thanks for yours
Hi,
I have a problem.
My test seems to keep on “refreshing” the page after login. This loops over and over.
Any ideas?
Thanks!
Hi there.
For some reason I can’t seem to get $fbme to work
I created new facebook application named dummytester
put index.php fbmain.php and facebook.php
changed $config['baseurl'] with index.php file
changed these appropriatly @ fbmain.php file
$fbconfig['appid' ] = “”;
$fbconfig['api' ] = “”;
$fbconfig['secret'] = “”;
I get the login button and do get logged in. If i am allready logged in i get the “facebook logout” button.
but i do not see the data that i am supposed to see if the php var $fbme was set to true.
please help
@Paul and @Yaary, read attentively the steps of this post.
http://thinkdiff.net/demo/newfbconnect1/php/index.php The demo is working nicely (there is no looping problem and no getting no data problem) and I published the source code in this article. Many other programmers also successfully used this code. So I’ve no answers for you.
@Mahmud, you created a very clear and forward tutorial
For some reason my code keeps on looping. Here is a link to it:
http://mypaintballcircle.com/app/index.php
Let me know if this loops from your computer.
Not sure if there are some strange setting on the server that I am using to host the code.
I will try to move this to a different server to test this.
Thanks for commenting back
Paul.
hmm your one is redirecting again and again. I am not sure why its redirecting in your server. If you want to check everything from me, then you can give me the ftp access and make me developer access of the facebook application. Then I can take a look what is actually happening. If you want then mail me.
just for the reecord, the first time i tried the code, i attached the code to a preexisting facebook application and got the loop as well.
I then went and changed migration settings and the looping stopped but in both cases, although I see a change in login logout button, no data
@Yaary, actually my facebook app is a pre-established app. I am going to scrap it and re-create it and see if that fixes the problem.
@mahmud, I will try Yaary’s suggestion and if it fails, I will shoot you an email with credentails. Thanks for your help
checkout my latest article http://thinkdiff.net/facebook/create-facebook-popup-authentication-window-using-php-and-javascript/ to solve your problem.
Hi Mahmud, I love the simplicity of tutorial and I’d have to agree with some of the others here that it’s more coherent and understandable than Facebook’s own documentation. Thank you so much for sharing your knowledge!
Just a little contribution for your blog: for those who’re unable to get valid information into $fbme, a simple solution was posted on PHP-SDK github… you will need to add this line to facebook.php under the public static $CURL_OPTS array:
CURLOPT_SSL_VERIFYPEER => false
Apparently, there seems to be a problem with authenticating the SSL certificate, so this line should solve the problem. Once you add this line, there’s no need for the Javascript popup workaround (although, even that is wonderful l’il piece of work!)
Yes, thanks for the fix for that. If you’re $fbme is null, this will fix it.
Thank You AJ
after adding the fix to facebook.php, it works fine.
And thank you Mahmud for a great tutorial.
Thanks for this post. It REALLY helped me out a lot.
Question: If I wanted to have the user fill in a status update, but delay the submission of that status update for another time, is that possible with facebook? I am able to do this with Twitter by storing the oauth oauth_token and oauth_token_secret and use it later to call the twitter api. Is the same thing possible here?
Thanks again!
@Fish, yeah you can do this. You’ve to seek offline extended permission from user and status update permission. If user approves offline permission, store the session key in your database for that user. Then when you will create
$facebook = new Facebook()object then assign the session using$facebook->setSession($usersession)code. And if user also approves status_update permission, you can now update user’s status behind the scene.Thank you of this
About fish’s post
what data comes to
$facebook->setSession($usersession)
to $usersession ?
I have got a oauth-token that contains | and – signs (pipe and minus separating numbers and chars..)
nice share..
can you give me an sample invitation using scripts sdk-php?
thank you..
@mahmud, Thanks so much. After playing around with it a bit more last night I came to realize thats how it works but have not implemented it yet. Do I save the entire session or just the “access_token”- Seems like I would save the full session, is that correct?
Also, I am trying to figure out how to post to an authenticated users PAGE instead of their profile. In the past I believe we had to use “enable_profile_selector” but I’m not sure how to get the page choices.
Thanks again!
Fish
Mahmud, congratulations for your posts. Are very interesting.
I’m trying to make this thing work in a FB application using canvas and Iframe.
No problem in chrome and mozzilla, but in Internet explorer 8 when the login pop up open there is an error “Page don’t load”
http://apps.facebook.com/questionariouno/
Whay i need to try is very simple:
I only need some data (username and email) of the customer that logins in the application, and your example is the only one that “almost work”. The other I find simply doesn’t work at all.
Any help?
Thank you.
@Ernesto, if you’re developing iframe base facebook app then follow my another tutorial: http://wp.me/pr3EW-sv I hope it will solve your problem.
How can i send gift from my application to selected users using Graph API. Please help with code…
This is a great tutorial for the Graph API! One question though, how do I get information from the user for their work experiences? In the JSON tree it is some kind of subtree and I wasn’t sure how to get to it, or display it using the following:
$userWork= $fbme['work'];
That (obviously) doesn’t work. I can get all of their basic info, but not their work stuff and anything else that is hierarchical in nature. Any help would be great, thanks
@pat, checkout my latest post http://thinkdiff.net/facebook/users-demographic-data-from-facebook/ you’ll get your answer there.
Thanks, much appreciated!!
Hi to all
I was wondering about the new Auth2.0 and the login button. I am trying to program a fbml based canvas application using flash as serverside.
I am trying to get the auth popup window to open automatically if user has not logged on or if user has nor autherized the application yet.
Any idea’s regarding what tools to use will be welcome
Brilliant – really useful. Been having some real problems implementing the Facebook Graph (mainly regarding auth/sessions), but this seems to have solved everything.
Thanks!
@paul how did you solve your looping problem?
I have same problem here
visit http://thinkdiff.net/facebook/create-facebook-popup-authentication-window-using-php-and-javascript/ and using the following technique you can solve your looping problem.
Thanks for the timely article featuring Open Graph.
A question though about using POST. I’m able to receive my user object, activities, statues, feed, posts etc, but my status does not update with this code, even when wrapped inside a if($session):
$faceboook->api(‘/me/feed’, ‘post’, array(‘message’=> ‘sample status message’, ‘cb’ => ”));
any thoughts? what am i missing?
thanks,
Ansdrew
Are you kidding me? The demo nicely working for updating status. Check the demo and code.
Wow Nice! Good job…
can I retrieve list of my application’s users using graph api or fql?
I think no. Using http://developers.facebook.com/docs/reference/rest/friends.getAppUsers this method you can retrieve user’s friends who has authorized the app. But I don’t fine any fql table or api by calling that you can retrieve all the users Ids of an application. If you explore this let us know the way.
Hi Mahmud,
Another great post. Thanks a lot!
I did everything that was asked.
pdownloaded facebook.php, created fbmain and index.php
But when i execute the index.php script, nothing comes up on the browser and I am getting the below error in my log file.
Uncaught QueryParseException: An active access token must be used to query information about the current user.
thrown in /home/wildfire/public_html/ignite/php/facebook.php on line 454
Any idea how i can resolve this?
Would appreciate your help greatly
Figured it out.. Thanks anyways
What was the solution? I’m getting the same error too
also I do
in spite of “stream.publish” method works well with this token
What was the solution? I’m getting the same error.
hi Mahmud,
why my page always refreshing after login/logout .. endless refreshing
thanks
Please check the following tutorial and update your code (this technique will help you to stop refresing) http://thinkdiff.net/facebook/create-facebook-popup-authentication-window-using-php-and-javascript/
This tutorial helped me a lot to move further with graph api. thanks
hi
i’m using your code in my new application but me session remains always null even i’m logged in. Plz help… Also what is replacement of require_login() function. if a user does’nt add application he/she should show allow screen how can we reach this using new graph api… thanks in advance…
Please read the article carefully, this article is for fbconnect base application. If you need help for iframe base canvas application development, please check all the comments, you’ll find another link about iframe application development.
Thanks for this article! It helped me so much. You give me a break..Thanks!
I just have some questions ^^ I was playing with the parameters using the PHP SDK and when I use “popup” as my display, it still takes up the whole page but the layout was moved to the left. It didn’t pop up. I don’t know what’s missing or what’s wrong.
Also, how can I set show-faces=true as a parameter(Login Faces Social Plugin). I don’t know if this is already possible in PHP SDK, there is no mentioned parameter in the source. In javascript it’s this
, but I want to implement it in PHP
I’m thinking right now, it can only handle extended permissions(req_perms).
Thanks again!
Ahaha I found your article about the popup…should’ve browse first before asking. Sorry, I’m just excited! You make it look so easy…better than Facebook API documentation ^^ Thanks!
I have read ALL the facebook.php code and then I found this, damn
GREAT WORK mahmud ahsan !!!
Mahmud thank you you’re the best
how do I do to show my last 10 status?
but I have a problem trying to display my feeds by calling $ facebook-> api (‘/ me / feed’);
nothing appears
thank you in advance
But i am having a basic problem.
i am getting the login url using getLoginUrl()
but when i am redirecting to that url, i am getting some different issues for different browsers.
my application is http://apps.facebook.com/helloworld_udvh/
issues i am getting..
=================================================================
Issue in IE7 Browser
=================================================================
There is a problem with this website’s security certificate.
The security certificate presented by this website was issued for a different website’s address.
Security certificate problems may indicate an attempt to fool you or intercept any data you send to the server.
We recommend that you close this webpage and do not continue to this website.
Click here to close this webpage.
Continue to this website (not recommended).
More information
If you arrived at this page by clicking a link, check the website address in the address bar to be sure that it is the address you
were expecting.
When going to a website with an address such as https://example.com, try adding the ‘www’ to the address,
https://www.example.com.
If you choose to ignore this error and continue, do not enter private information into the website.
For more information, see “Certificate Errors” in Internet Explorer Help.
=================================================================
Issue in Google Chrom Browser
=================================================================
This is probably not the site you are looking for!
You attempted to reach http://www.facebook.com, but instead you actually reached a server identifying itself as a248.e.akamai.net. This
may be caused by a misconfiguration on the server or by something more serious. An attacker on your network could be trying to
get you to visit a fake (and potentially harmful) version of http://www.facebook.com. You should not proceed.
=================================================================
Issue in Fire Fox Browser
=================================================================
Secure Connection Failed
http://www.facebook.com uses an invalid security certificate.
The certificate is only valid for the following names:
a248.e.akamai.net , *.akamaihd.net
(Error code: ssl_error_bad_cert_domain)
* This could be a problem with the server’s configuration, or it could be someone trying to impersonate the server.
* If you have connected to this server successfully in the past, the error may be temporary, and you can try again later.
Or you can add an exception…
===========================
code i used:
===========================
<?php require '../../libs/facebook.php'; define("FACEBOOK_APP_ID", ''); define("FACEBOOK_API_KEY", ''); define("FACEBOOK_SECRET_KEY", 'MYAPPSECRETKEY'); define("FACEBOOK_CANVAS_URL", 'http://apps.facebook.com/helloworld_udvh/'); $facebook = new Facebook(array( 'appId' => FACEBOOK_API_KEY, 'secret' => FACEBOOK_SECRET_KEY, 'cookie' => true, 'domain' => 'udbhavah.com' )); $session = $facebook->getSession(); if (!$session) { $url = $facebook->getLoginUrl(array('canvas'=>1,'fbconnect' => 0)); //echo $url; echo "top.location.href = '$url';"; } else { try { $uid = $facebook->getUser(); $me = $facebook->api('/me'); $updated = date("l, F j, Y", strtotime($me['updated_time'])); echo "Hello " . $me['name'] . ""; echo "You last updated your profile on " . $updated; } catch (FacebookApiException $e) { echo "Error:" . print_r($e, true); } } ?>please help me on this.
thanks in advance.
srinivas p.
Dear Srinivas, I couldn’t find this type of problem for my application. Checkout the tutorial, demo and full source code from here http://wp.me/pr3EW-sv
Hi mahmud,
could you pl. open my app
http://apps.facebook.com/helloworld_udvh and let me know if you faced any issue in that?
Thanks in advance,
srinivas p.
Hi mahmud,
thanks for your prompt response.
even i am not facing the issue for my app
http://apps.facebook.com/helloworld_udvh
when i am trying after my laptop is connected to VPN.
Without VPN connection i am getting this error.
Can you pl. help on this..
thanks in advance,
srinivas P.
This demo really helped me out in regards to formatting things nicely and understanding what was going on a bit better. Does anyone know of good examples/tutorials on formatting the returned graph array data in CSS?
I am very newbie to facebook’s programming.
I tried to follow a step by step
I found this error “Facebook needs the JSON PHP extension” when I run the application.
Do I miss some files to run the apps?
Can you please help me how to solve the problem?
Thanks.
In your server you must have to installed json php extension. Please search in google before asking any question. You’ll find 99% answer in google. Thanks
Do you have any idea how to integrate this with WordPress?
I am able to use this in the header section of my wordpress site, but somehow the $session, $uid, $fbme variables are lost or cleared in other sections.
In my comment section, I call if($fbme) and it returns null. Though from my header, it shows I am logged in.
Thanks for the article and any help!
christopher
very good work
Is there way to get users real email? Requesting email parm (‘req_perms’ => ‘email’) I get only user facebook proxy mail.
Hi! great tutorial.
I can’t seem to get $session even if I’m logged in and authenticated. It’s just null. The FB javascript indicates that I’m logged in.
UPDATE: It works when I try your demo. But on my site I get no session and thus no data.
I’m running my site on localhost btw, and that’s what I’ve put in the app settings. I now for a fact that authentication works because it works with the JS SDK, but I want to use the PHP SDK.
I’m having the exact same problem, except i’m not running on localhost, just directly accessing the site through IP.
I can’t get a valid session… any help?
Make sure your curl and json extensions are installed and enabled. Also, make sure you have SSL CA certificates installed (type: sudo apt-get install ca-certificates). This should cure your problem. Good luck!
Thanks Man , U are the Best , Excellent Article, Its working perfectly.
Can u plz also tell me how can i do the wall posting frm Graph API.
Excellent tutorial – Thank you for taking the time to post this!
Thanks for the tutorial!
I only don’t know and understand how to custom the output content.
Right now I’m getting all the content into an array as:
Array
(
[id] => 123456789
[name] => Gil
)
But I don’t want it to be in array
how can I custom the output please?
For example I want something like this:
$user['id']
$user['name']
Hi, im trying to set up what you described. I’m getting problems. When I run it on my server i get the same but without de button. Don’t no if i’m doing something bad o what. I’ve xampp latest version and curl, json on.
Can you send me via mail, the files, Index.php, fbmain.php
Thanks a lot. My boss is going to killme if I don’t connect this soon.
Hi Mahmud,
thanks for your great tutorial!
I’m having troubles when I put this code onto my server, I’m getting a timeout error and I don’t understand why. Maybe you have a clue about what is happening.
That’s what I get:
[result:protected] => Array ( [error_code] => 6 [error] => Array ( [message] => name lookup timed out [type] => CurlException ) ) [message:protected] => name lookup timed out [string:private] => [code language=":protected"][/code][/code] => 6 [file:protected] => /var/www/vhosts/xxxx.com/httpdocs/php/facebook.php [line:protected] => 513 [trace:private] => ArrayThank you!
Hi Dani,
i’m also having the same problem.
curl on “api-read.facebook.com” always return name lookup time out.. its frustrating
Have you found any solution?
thank you.
best regards,
James
same problem here…..
does anyone knows the answer?
Hi, Same problem here too!
I get a time out error, then later my app starts working again!
It only happens during the day….
What should I do to determine the problem?
This post on the FB DEV API FORUM has some interesting information:
http://wiki.developers.facebook.com/index.php/Talk:Users.getInfo
It talks about the nameserver timeout. I think Facebook’s DNS Servers are having a problem…
I think i’ve figured it out.
Adjust the CURL timeout settings in the facebook.php
Find this var and adjust to increase the connection Time Out.
CURLOPT_CONNECTTIMEOUT => 30
This is my site, where I’m trying to start a forum about
facebook application development. I’d really like some support if anyone’s willing to give some, I’ll share more of what I know!
http://green.cx (Forums link is at the top of the page)
Thank you so much for your great tutorial.
Let me know how can i get email id of the users who were logged into my site using facebook id. This because of my database maintenance of my project that who were logged into my site by using their facebook email id and password.
By the whole i can i got the email id of user who were logged into my site.
Just provide the email extended permission as my example, then using fql query you can retrieve his email address easily. You can also check the example http://thinkdiff.net/demo/newfbconnect1/php/index.php and look User Information using Graph API this part. You will see your facebook email there. So read the code and use it in your site. thanks.
hi
ur application is great..
i have some problem ,i.e.
i want to login in facebook without using fb:login button..
Is it possible to allow a user to enter username and password to a Facebook account in a 3rd party application (outside of the Facebook system), and then submit it to the Facebook API to get access?
please reply…
thanks
please reply….any thing u know about it…
Thank you so much for your great tutorial.
i am having one problem by using facepile to my project.
i am getting below error when i click facepile
“The Facebook Connect cross-domain receiver URL (http://static.ak.fbcdn.net/connect/xd_proxy.php#?=&cb=f34e18026c4e01&origin=http%3A%2F%2Fwww.promolife.com.au%2Ff2f0bf484991814&relation=parent.parent&transport=postmessage) must have the application’s Connect URL (http://promolife.com.au/) as a prefix. You can configure the Connect URL in the Application Settings Editor.
”
why do i get this error . how can use facepile in php
Raja, you get this error because the Connect URL in the application settings in facebook is empty. You can provide the same canvas url for the connect url and it should work fine. Try it out.
Sri.
thanks, good tutorial
It was of great help
Hello mahmud,
I follow you JS sdk tutorial and it worked fine.
But now when doin the php sdk no luck.
the page always return empty.
I use js-sdk to login and hope to use php for fetch data.
and i don’t promt errors (ie: curl and json). Just blank.
please help.??
Found the error. appId is not workd php to javascript.
hardcode the appId. the it works..
thanx. great tutorial.
Assalamu’alaikum Mahmud. Thank you for a very good tutorial.
But I have one request, can you teeach us how to upgrade current WordPress plugin that using old Facebook platform to use this new Graph API?
I’m currently using the WP-FB-AutoConnect plugin, but the creator of this plugin seems kinda busy to upgrade it.
Help from other also appreciated. Thanks.
hallo mr mahmud n all….
i have error “Protocol https not supported or disabled in libcurl in facebook connect”
how to solve the problem??
plz help me…
Libcurl in my hosting Enable.
dear Mr. Mahmud ,
This is what all I have done….
but can you provide me the example use of the function users.getStandardInfo
it would be great help to me…….
Thanks for this fantastic post!
I spent days looking for a good way to update a users facebook status through PHP. This explains it!
Thanks!
Thanks, great tutorial. It helped me a lot. With all the different methods on how to connect on FB available, it can be hard to figure it out!
Great article!
Just one question about security in general. How can I restrict direct download of my php files from people that want to look at my script code? I don’t want people looking into my index.php file!
Please let me know how/if this is possible.
Kind regards,
Noah.
Is it also possible to set a parameter for Login to turn into Login with Faces in PHP SDK? Thanks
Hi Mahmud,
Thanks again for this useful tutorial, I just got a question, how do i get the id of the last uploaded image?
I try this:
SELECT pid FROM photo WHERE aid IN ( SELECT aid FROM album WHERE owner=’100001106637062′ ) ORDER BY created DESC LIMIT 1
but it returns this : “pid”: “100001106637062_111810″
which is the user_id followed by the image id. not sure how to separate them My ultimate goal is to redirect user to the last image uploaded on his/her account. Please help,
Thanks
Khalid
This question isn’t related with this article.
Hi Mr. Mahmud ahsan,
really gr8 work man..
..
I face err while running below code :
=============================
hello
Exception is CurlException: 6: name lookup timed out
<?php
session_start();
require_once 'src/facebook.php';
require_once 'config.php';
$fbid= $_REQUEST["fb_sig_user"];
$logo= $_REQUEST["imgname"];
echo "hello “;
try
{
$fql = “SELECT name, pic_big FROM user WHERE uid=’$fbid’”;
$param = array(‘method’ => ‘fql.query’,'query’ => $fql,’callback’ => ”);
$fqlResult = $facebook->api($param);
}
catch (FacebookApiException $e)
{
echo “Exception is “.$e;
}
print_r($fqlResult);
?>
==========================
If possible please look into it..
Thanks in advance.
I’m not facing such type of error in my applications. So no idea.
Hi Manish,
change it to new graph api call,
$_friends = json_decode(file_get_contents("https://api.facebook.com/method/fql.query?query=".urlencode($fql)."&access_token=".$facebook->getAccessToken()."&format=json"));hello sir,
In sort unable to execute fql properly.
$fql = “SELECT name, pic_big FROM user WHERE uid=’$fbid’”;
$param = array(‘method’ => ‘fql.query’,’query’ => $fql,’callback’ => ”);
$fqlResult = $facebook->api($param);
=========================
out put is :
Exception is CurlException: 6: name lookup timed out
Sir any idea ??
Please check it http://forum.developers.facebook.com/viewtopic.php?pid=241263
there are no any solution..
if u have any idea how to execute query with new api .. pls let me know.
It would be gr8 help
Thanks in advance..
Below code works in my application. So i don’t know why its not working in your case.
//fql query example using legacy method call and passing parameter try{ //get user id $uid = $facebook->getUser(); //or you can use $uid = $fbme['id']; $fql = "select name, hometown_location, sex, pic_square from user where uid=" . $uid; $param = array( 'method' => 'fql.query', 'query' => $fql, 'callback' => '' ); $fqlResult = $facebook->api($param); } catch(Exception $o){ d($o); }great article, thanks, btw @srinivas : hello Mr. Srinivas, how are you?
Dear Mr. Mahmud….
how to add action link on a wall…
I have tried like this
$fbme = $facebook->api(‘/me’);
$attachment = array(‘message’ => ‘hello’,
‘name’ => ‘hello 2′, ‘caption’ =>’hello caption’ ,
‘link’ => ‘link hello’,
‘description’ => ‘nothing’,
‘picture’ => ‘http://example.com/pic.jpg’,
‘actions’ => array(array(‘name’ =>’ this action’,
‘link’ => ‘http://example.com’) );
thanks for your hands…
action links should be json encoded.
function streamPublish(name, description, hrefTitle, hrefLink, userPrompt){ FB.ui( { method: 'stream.publish', message: '', attachment: { name: name, caption: '', description: (description), href: hrefLink }, action_links: [ { text: hrefTitle, href: hrefLink } ], user_prompt_message: userPrompt }, function(response) { }); }Hi Mahmud Ahsan,
I have gone through ur nice post, started implementing it, unfortunately from the 2nd step itself, i had error
I am getting null value for the $facebook->getSession(); even if i login to the facebook.
please let me know how it is happening.
I search in google but i fund some complected step
http://blog.theunical.com/facebook-integration/5-steps-to-publish-on-a-facebook-wall-using-php/
I have to go through this steps??
What is my need is, I will be having some face book id in my table. we i clicked a button from my facebook. I need to publish wall to all this id. Please let me know whether is possible or not?
waiting for ur valuable information
with regards
Shanavas
Thanks Mr. Mahmud…
I want to do adding action_links using php? thanks you share using javascript..
Is there any code using php?
try { $actions = json_encode(array(array('text'=>'Click Here', 'href'=>'http://thinkdiff.net'))); $param = array( 'method' => 'stream.publish', 'callback' => '', 'message' => $msg, 'attachment' => '', 'action_links' => $actions, 'target_id' => '', 'uid' => '', 'privacy' => '' ); $result = $facebook->api($param); } catch(Exception $o) { }I have followed the same thing but I can’t seem to get it to work.
$facebook = new Facebook(array( 'appId' => $app_id, 'secret' => $secret, 'cookie' => true, )); $msg = “hello”; try { $actions = json_encode(array(array('text'=>'Click Here', 'href'=>'http://thinkdiff.net'))); $param = array('method' => 'stream.publish', 'callback' => ”, ‘message’ => $msg, ‘attachment’ => ”, ‘action_links’ => $actions, ‘target_id’ => ”, ‘uid’ => ”, ‘privacy’ => ” ); $result = $facebook->api($param); }catch(Exception $o) {}Please never mind the quotes, it’s not displaying properly here hehe. Thanks for any suggestions.
Dear Mr. Mahmud…
do you know how to fix it, if I update status like this “I can’t wait” the wall of facebook display “I can't wait” , thanks for your hands…
Best Regards,
Saiful Amri (Dagohill Founder)
thanks Mr. Mahmud….
the last my question is how to fixed problem about special character
thanks for your all hands…
Best Regards…
Saiful Amri
Great!!! @mahmud ahsan says on July 16, 2010 at 10:18 pm
It’s worked 100%
Thanks
Hello Saiful! I just like to ask how do you get it to work? I can’t get it to work. If you can help me figure out what am I missing here:
Thank you!
Hello Patrick…
The first, is your application using latest facebook.php ?
then before execute the code above have you check your SESSION ?
example :
$session = $facebook->getSession(); $uid = $facebook->getUser(); $fbme = null; if ($session) { //put the code here... }Thanks, I hope it can help you…
I am sorry I mean for Justn Cribb,
, but it’s for at all too…
btw…
Justn Cribb, I used the code for publish stream only and not for update update status…
thanks
Yep. I am trying to convert my Post action(which is working) to Publish Stream so I can have action links.
$post = $facebook->api(‘/me/feed?access_token=’.$this->facebook_oauth_token, ‘post’,
array(‘message’=> $message, ‘name’ => $name, ‘link’ => $link, ‘caption’ => $caption, ‘description’ => $description,
‘picture’ => $picture));
I’m curious, why is there no access_token param for publish_stream? I tried adding it, but it doesn’t work. Did you just do that getSession and followed Mahmud’s code…like copy-pasted it to test and it worked already? Or did you have some tweaks?
By the way, thanks for replying Saiful. I appreciate it a lot. I’m kinda stuck haha!
hello Justn Cribb,
yes, the first I just copy and paste code from Mr. Mahmud (thank you so much) and then I try and it works, actions_links is displayed, for update status does not need action_links, or attachment, action_links is just for Publishing a Post Containing an Image, Action Link, and Custom Metadata or Publishing a Post Containing Flash, Action Link, and a Target.
access_token param is saved in session or cookies…
does your 2nd code above is for update status?
example for update status I should use like below :
//facebook status update // Create our Application instance. $facebook = new Facebook(array( 'appId' => $fb_appid, 'secret' => $fb_secret', 'cookie' => true, )); $session = $facebook->getSession(); $uid = $facebook->getUser(); $fbme = null; if ($session) { $fbme = $facebook->api('/me'); try { $statusUpdate = $facebook->api('/me/feed', 'POST', array('message'=>$msg, 'cb' => '')); } catch (FacebookApiException $e) { //d($e); } //end facebook status update ///for stream publish I should use like below: actions = json_encode(array(array('text'=>'Dagohill', 'href'=>'http://dagohill.com'))); //facebook stream publish // Create our Application instance. $facebook = new Facebook(array('appId' => $fb_appid, 'secret' =>$fb_secret,'cookie' => true,)); $session = $facebook->getSession(); $uid = $facebook->getUser(); $fbme = null; if ($session) { try { $message = " just leave a news "; $attachment = array( 'name' => $title, 'href' =>$href, 'caption' =>' rated it 5 stars', 'description' =>$summary, 'properties' => array('category' => array( 'text' => 'news', 'href' =>$href2), 'ratings' => '5 stars'), 'media' => array(array('type' => 'image', 'src' =>$imageurl, 'href' =>$href)),'latitude' =>$latitude, //Let's add some custom metadata in the form of key/value pairs 'longitude' => $longitude); $attachment = json_encode($attachment); $param = array('method' => 'stream.publish', 'callback' => '', 'message' =>$message, 'attachment' => $attachment , 'action_links' => $actions, 'target_id' => '', 'uid' => '', 'privacy' => '' ); $result = $facebook->api($param); }catch(Exception $o) { // } //end facebook stream publishI hope it can help you….
thanks
Hello Saiful! I’ve been pretty occupied lately, but I just dropped by to thank you…your solution worked! Thanks for sharing your knowledge ^^
Saiful,
Could you please the same functionality with javascript sdk
Thanks,
Joe
I mean provide the same functionality with Javascript sdk
first off, i want to say “thank you” for this great tutorial; i’ve been wrestling with this all week and yours is the first i’ve come across to make real sense and actually work.
however, there’s a small error here that i needed to fix to get this code to work:
in the form that submits a post to the wall, there is a line that reads:
action=”"
i had to change this to the following for it to post properly:
action=”"
i also had to adjust the permissions, which you touched on in tutorial.
i hope that this is helpful; this is a great reference and i just want to make sure it works! thanks again!
my above comment didn’t format correctly, it did not display the code parts! let me try again:
in the form that submits a post to the wall, there is a line that reads:
action=”\”
i had to change this to the following for it to post properly:
action=”\”
i hope this displays correctly…
trying again…. screw it, i’m taking out the carrot marks; i hope you guys can figure out what i’m talking about:
in the form that submits a post to the wall, there is a line that reads:
?=$config['baseurl']?
i had to change this to the following for it to post properly:
?php echo $config['baseurl']?
this tutorial is really good
but i find the demo does not works well
$session=$facebook->getSession();
DO $session get value by GET?
is there any method to get $session by POST or other way
Can you pls post the code snippet in PHP, for posting comments to logged in user wall using graph API thru CURL.
I could not really figured out doing this.
really good!!
Can you tell me how I can take all user id of my facebook application (by fql)??
Thank you Mr. Mahmud for this tutorial… it helps me a lot to understand how the new facebook API works.
Is it possible to check what permissions the auth_token has (with latest php sdk and opengraph)?
I also would love to know the answer to this.
I love this tutorial, saved my time…Good work mahmud ahsan
Hi, gr8 tutorial.
How i can get all events that i’v created and shared on my wall?
Thanks in advance.
there is event class in Facebook API,by which u can fetch and create events from ur application
Hi,
For those using coldfusion, i have ported the facebook php-sdk to cfml.
cheers
marcel.
http://github.com/quicken/facebook-cfml-sdk
@nidhi: is in facebook.php ?
How i can instantiate de event class?
I m working on c#
and using latest version of facebook api.
and i dont think that is there any difference in c# and php api.
i used following code which is in c#
System.Collections.Generic.IList events = api.Events.Get();
convert it into php.
hi,
i am trying to post the comment on facebook status,
can any1 help me by using the same api
try {
$statusUpdate = $facebook->api(‘/me/feed’, ‘POST’,
array(‘comments’=>$comment, ‘cb’ => ”));
} catch (FacebookApiException $e) {
//d($e);
}
HOW TO ADD COMMENT ON PARTICULAR STUTAS ??????????//
Plsssssssss……………,, can any1 help??????????
ok nidhi i try;)
hi
ur application is great..
i have some problem ,i.e.
i want to login in facebook without using fb:login button..
Is it possible to allow a user to enter username and password to a Facebook account in a 3rd party application (outside of the Facebook system), and then submit it to the Facebook API to get access?
please reply…
thanks
“Until you don’t install curl and json extension this sdk will not work.”
How to add application in Facebook page?
You’ve to create facebook tab application, please check my other tutorial. http://thinkdiff.net/facebook/develop-customize-facebook-application-for-fan-page/
please reply of my query….
hello sir,
one quick question can we display like button in gaph api without JS and iframe..
Thanks in advance for your kind reply.
hi,
do you have any detail about how to incorporate the login feature of facebook using ONLY PHP and not FBML and stuff so that user can login and allow him to post via PHP from mysite.
if so kindly let me know.
You can check this article http://thinkdiff.net/facebook/create-facebook-popup-authentication-window-using-php-and-javascript/
Urgent.. I have got a problem trying to follow your step. After prompted login and was logged in, it will have the FacebookApiException Object showing that Protocol https not supported or disabled in libcurl and the type is CurlException.
How am I able to solve this problem ?
Im hosting on site11.
My application site is http://fbposting.site11.com/, btw do any free website hosting support http and libcurl ?
Thanks for the good article.
I need two helps:
(a) how can I change the button name text “Facebook Logout” to Facebook & My Siste Logout”.
(b) How can I call the php function to do the Facebook Logout uisng php? Because I need to execute the Facebook Logout, when someone removed their account.
checkout this tutorial http://thinkdiff.net/facebook/create-facebook-popup-authentication-window-using-php-and-javascript/ to know how to generate logout url. Hope you can now call your site logout function then the logout url generated.
Dear Mr.Mohamad,
I am beginner to Facebook Application.I taken your sample and execute it.All Works except Update Status.Returns the follwing error,
[error] => Array
(
[type] => Exception
[message] => (#200) The user hasn’t authorized the application to perform this action
)
Please help me to fix this…
Thanks in Advance
DineshKumar
thank you for great tutor. i think i followed all steps ,but i get error when i go to the application page :
Parse error: syntax error, unexpected T_INCLUDE_ONCE in /home5/xxxxxxx/public_html/connect/index.php on line 2
where line 2 is : include_once “fbmain.php”; what i doing wrong? can you help me please.
checkout if you place fbmain.php at that directory or not.
yes its same directory :
facebook.php
fbmain.php
index.php
i have this three file in there
AWESOME Tutorial!
But how do you put other data in an array?
For example if you grant permission to share user_activities. How can you put it in an array like the array $fbme?
@Joe says – August 25, 2010 at 12:28 am
You can find an example of using javascript in this tutorial, please check again…
Hi! First of all let me tell you that I looked around for lots of tutorials and yours is the only one that helped me!. Now, I’m getting an error when, after been logged using your example in my server and getting an account data, I go back to facebook, log out, go back to the example (which I kept open in another window) and refresh the page…I get an error like this:
FacebookApiException Object
(
[result:protected] => Array
(
[error] => Array
(
[type] => OAuthException
[message] => Error processing access token.
)
)
[message:protected] => Error processing access token.
[string:private] =>
=> 0
…
and it goes on. I read that it may be a token expiration problem and they say that I have to get offline_access permissions…so, how do I do that with your code?
A similar thing happens if instead of logging out from facebook website, I login again with a different account. If I refresh my page I get the same error for 1 sec and then it refreshes with the correct data.
BTW….thank you so much for the tutorial!
Good, solid example. Very good thanks!
Hi again, well I found a way around the issue I mentioned before. Since that, in a practical way, this error didn’t interfere with the functionality of the website because the connection with facebook worked it’s just don’t I don’t like an error message printed in half your screen, I removed your Exception routines. Now it doesn’t show the error and it works.
If anyone has this issue too (read my comment on August 27 11:26pm) and found a way to actually solve the problem and just not hide it please let me know!
Hi Mahmud,
Thanks for this great tutorial, I have been struggling with this for a while.
Any idea how to post an event?
I had this application working on a server through Joynet’s developer program then switched to their paid service and it broke.
I changed the website config in the Facebook dev app, so its not that. I can change the website back and forth from the old server to the new. The old will always work and the new will not.
The app running on the new server lets me login into Facebook, accept the extended permissions and then redirects me to the appropriate place but it acts as if I am not logged in.
Any ideas? I have been going over code and server configs for two days now.
Hi,
Am a beginner and trying a FB application using Graph API. I tried the examples given on this site.
But always $facebook->api(‘/me’) returns NULL and throws exception. I tried all the suggestions mentioned in the posts but unable to figure out the reason.
Can anybody please help me.
Thanks in advance.
Regards,
neetu
Neetu,
What is the exception that it throws?
Hey John,
Thanks for replying.
I just solved the issue. It was not resolving the DNS for graph.facebook.com from my server.
Thanks
neetu
If someone can help me with this error y dont know what to do…
i get an FacebookApiException Object
url http://www.fbatp.webuda.com/index.php
Please Help
Hi,
I copied the code as is, but I keep getting the following when I browse the facebook App URL:
Application Temporarily Unavailable
The URL http://socialarabia.net/wordpress/fb/phpsdk/src/ returned HTTP code 200 and no data.
Sorry, the application you were using is experiencing a problem. Please try again later.
Update:
i tried debugging the code line by line in the fbmain.php
)
I commented all the lines of code and started removing them one by one ( I know.. crazy
it seems I can get away with
<?php
$fbconfig['appid' ] = "your application id";
$fbconfig['api' ] = "your application api key";
$fbconfig['secret'] = "your application secret key";
include_once "facebook.php";
But the minute I add the try statement I get the error code 200 and no data returned!!!
Any thoughts?
some more Update:
Ok, the problem is with JSON! i am not an experienced developer but reading carefully through your article and doing some research I implemented this code to see whether I can make JSON calls
$input = ‘{ “test” : 12121211212121 }’;
$val = json_decode($input, true);
print $val["test"];
and I received an error.. I wonder if I can still make JSON calls on Dotster shared hosting
Any thoughts anyone?
Superb job of explaining each part. My app was not working before I read this article … now it’s working fine!
Thanks
Mahmud, your tutorials have been a huge benefit to me! The facebook documentation is rubbish
If it wasn’t for your excellent tutorials, I still would not even know where to start! Thank you thank you thank you for posting these and explaining everything so well!!
Something I couldn’t find mentioned in your blog (but maybe its there) is how to post to a Facebook page as the page admin and not as the user. I spend days looking for this, and eventually found some sample code here that works (Thanks to Matt Burton!): http://bugs.developers.facebook.net/show_bug.cgi?id=10005#c139
Just posting this link here for others, as I have seen many people ask this on the facebook forums, and I can see many people come to your tutorials for help so this might help them too!
Could you show me how to connect cakephp with facebook?
I want to use graph api in cakephp, but i don’t understand how to apply sdk-php into cakephp like you have done above…
Thanks for your help!
when i am trying to integrate it i am getting this error
API Error Code: 100
API Error Description: Invalid parameter
Error Message: next is not owned by the application.
please help me to remove it
thanks
Hi guys, this is probably a noob question, but im not getting any session or session NULL if i var_dump, can anybody help me?
Hi i was wondering if someone could help me out….. i have read tons of tutorials but none really apply to my situation or i cant get it to work because im not exactly sure on what to do…i know a little about php but im no rocket scientist when it comes to this….. i have tried a bunch of different ways to implement this on my site and im not sure what files i am suppose to edit i am trying to get t he facebook connect on a software called phpbb3…. i have it installed on my server .. most tutorials dont explain or show how to implement this on a forum and since things have changed at facebook in 2010 not many people have updated videos or anything to show how it is donei have been messing with this for about 5 months now with no sucess on getting it to work so if someone could help me out i would be forever greatful you can contact me via email if anyone wants also i already created a developer app … that part was easy all the other stuff is hard and cant figure out..
If anyone hit fatal error complain about:
Cannot use object of type stdClass as array
for
$param = array(
‘method’ => ‘users.getinfo’,
‘uids’ => $fbme['id'],
‘fields’ => ‘name,current_location,profile_url’,
‘callback’ => ”
);
just change ‘uids’ => $fbme['id'], to
‘uids’ => $fbme->id,
Hello,
nice tutorial. I wanted to post a message in my Facebook Wall through my site and I used it. It works fine in mozzilla but I can not post anything on IE, safari and Chrome. What could be wrong?
Thanks
There is obviously a lot to know about this. I really didnt have a clue. Took me time to read all your posts, at least most of them, but I really enjoyed your blog. It proved to be Very helpful to me and I am sure to all the commenters here! It’s always nice when you can not only be informed, but also entertained!
I have written PHP example code for beginner Facebook application developers.
Easy to use
Easy to deploy
Features
1. Configuration setting config.php
2. Built-in Admin panel, including following
Ads Module (Google, Images, SWF, Text etc)
Users Management, (send message, user listing, delete, etc)
3. Language Class
4. Categories management class up to unlimited hierarchy
5. Other features like ready made rating script built-in .
For Demo and Download Code
http://apps.facebook.com/itsiframeapp/
Hey I am trying to get the list of friends of my friends is tehre any way to access them.
You’ve to do a trick in this case, when a user logged in, retrieve all his friends and save those ids in your database. So when you need a person’s other friends just retrieve friends ids from your database.
How do I request for extended permissions using the Graph API and PHP SDK ?
Checkout the authentication code where you can easily provide extended permissions.
I checked it but couldn’t find the syntax to ask for extended permission using Graph API and PHP .. Can you point me to it ?
May be this can lead you to the proper things:
public function getMorePermissionUrl($params=array())
{
// WARNING: scope here not req_perm – ?!?
return parent::getUrl(‘graph’,
‘oauth/authorize’,
array_merge(
array(
‘client_id’ => self::getAppId(),
‘redirect_uri’ => self::getCanvasUrl(true),
),$params));
}
That is php_sdk but the same can be achieved thru JS
Regards,
So with PHP SDK and Graph API.
$facebook->api(/oauth/authorize,array(‘read_stream’,'user_birthday’);
Is this fine ?
Using Graph API for retreiving user info of a particular user with the UID,
Can I send multiple UIDs in a single API call ?
Thank you very much! Your posts helped me a lot!
yeah, it helped me a lot too, thanks
Thank you very much for this tutorial, with this SDK how can we post news and wall with out changing the status
great post, this is what i need.
anyway, to develop an facebook app i just need PHP-SDK only? i mean, no need to use jscript-sdk ?
In step 3, you’ll see javascrip sdk is loaded by the following code.
(function() { var e = document.createElement('script'); e.type = 'text/javascript'; e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js'; e.async = true; document.getElementById('fb-root').appendChild(e); }());thanks man…
Hello,
How can I skip login and allow access steps to be automatically. For example if someone is logged in on my website and I have already all information like user credentials and api data?
Hi, mahmud, Does you tutorial will work on localhost? I’ve tried to copy paste all your code in my localhost, It’s not working at all. But when I try it on my live server, it works very well… Is there any way to make it works on localhost? since it’s not so comfortable to do the stuff on live server. I’d rather test everything from my localhost.
It will not work on localhost unless you setup facebook settings to connect on your project on port 8080. This will work -> localhost:8080. This will not work -> localhost.
Hi
I am trying to acces the location of my friends and some other information of my friends.I have tried so many ways but i am not being sucessfull to do so. Can any boady help me Plz..
Imran Athar
Very nice and clear tutorial!
I can successfully access data with graph api call.
However, the response time is kind of annoying.
Each api call costs about 1~2 seconds.
If a page needs to call api 5 times, user will wait up to 10 seconds.
Does someone suffer from the same problem and have good workaround?
Thanks.
So better you cache information those are frequently need.
Didn’t anyone changed the api functions to get the user credentials for i.e. xml file (not ask user to type them) ?
So, I managed to put this into a module for Joomla, uhm but Idk why it does not publish. maybe I did something wrong.. o.O I followed ur steps tho..
Well you can check my website if u want to see it.
Regards =)
Erick
Nevermind it worked, I guess I had to wait a little while
.. niice nice
hy,
First of all, thank you for this great tutorial.For two days i’ve tried running this example, but i’m stuck(i’m new with php and facebook apps) ..
I can’t get the user’s real email address ! I only get facebook proxy email adress…
my application is at: http://www.mty.ro/tombola/index.php
Thanks!
It depends on your user, if user allow his real email address then you’ll get it otherwise you’ll get proxy email. We’ve no control over user’s choice.
well, the thing is that using the same user profile, i’ve installed both my app and the demo here http://thinkdiff.net/demo/newfbconnect1/php/index.php
and the difference was that for my app, the default option for mail was to permit the use of proxy email, while when installed your demo app, the default option was the real email adress…. I can’t figure out whi this behaviour occurs …
Hi,
Its a great tutorial. I could understand the whole FB connect process in 10 min. Thanks for the great work! I appreciate your effort.
I’ve successfully implement this code on my localhost, but the results seems very unstable, it often shows SSL connection timeout exception. Althought, not all the time, but almost 70-80% of api calling always resulted with that exception. I’ve add CURLOPT_SSL_VERIFYPEER => false in $CURL_OPTS array, nothing changed. It still showing that annoying exception.
Is it because I use it on localhost instead of live server?
Thank you! Your posts helped me a lot!
Mahmud, congratulations for your posts.
I’m trying to make this thing work in a FB application.
No problem in chrome and mozzilla, but in Internet explorer 6 when i click login button. Pop up open after logedin with my FB account its shows empty page….
HI Mahmud i need ur help..Plz guide me.This is my mail id php.sathish@gmail.com
The same thing occur in Ur Demo URL.In IE 6
http://thinkdiff.net/demo/newfbconnect1/php/index.php
For Sathish
Facebook does not support IE6.
Move on Sathish…the giants have already moved on, drop IE6.
If Microsoft is not going to take drastic action, Google will. YouTube, the Google owned video sharing site has long ago announced that it would no longer support IE6. Now Google is taking it one step further by announcing that it will no longer support IE6 on its Google Docs and Google Sites services as of March 1. – http://ow.ly/37hx0
dear mahmud thanx for the post, it help me to understand a lot
.
Hi mahmud ahsan, can u tell me how to install curl and json extension?
It depends on the operating system and server. Please search in google you’ll find the solution.
Hi Mahmud
Thanks for the great tutorial. I have one question, and maybe anyone will be able to help me.I have been using a lot of your code an been looking at a lot of the facebook documentation. My question is, on all the facebook examples, the call contains the access token.
/me/likes?access_token=…
I have played around with the code for a couple of weeks, and so far, I have not used the access_token in any of my calls, whether to retrieve info or post.Can anyone tell me why this is, and if its wrong to do so?
Kind Regards
Hi Cuan! To avoid calling the facebook api to generate oauth token, you save the access token in the database instead. This token may or may not expire depending on the permission you requested from your users. If you include Offline_Access permission, the token will not expire. You can print_r the session and play around with it so you’ll see the difference between having an offline_access permission and not including it in your permission. ^^
Hi Justin, thank you very much for the reply. My problem is more of understanding when to use access_token in api calls. Like I say, I use a lot of the code on this site, and so far, have not needed to safe the access token at all, or even use it in any of my calls.
I can send you through some code examples. When you ask for permissions on the login but, does it mean that you can access these things without using access codes.
Thanks in advance
You’re welcome. I’d like to explain it further, but I’m currently at the office…sneaking this reply to you haha! You can email me your code samples or inquiries at ian.moone77@ymail.com. I’d be happy to help based on my facebook dev experiences^^
Thank you very much. Just sent you a message. Thanks
Hey,
Thanks for this lovely tutorial. Well explained!
–
Shishir
hello,
your tutorial is wonderful. could you by chance give a quick example of how to access a friend’s music section of the info page. calling /uid/music returns an array of JSON objects but im not sure how to deal with them in PHP. even a short answer about how to approach this would be very helpful.
cheers.
Hi, I created a facebook application called Cellthis. And used the above code. Clicking on the login button gives me the following error –
An error occurred with Cellthis. Please try again later.
API Error Code: 100
API Error Description: Invalid parameter
Error Message: next is not owned by the application.
I think I am doing something wrong while creating the application. Can you please help.
Fixed it. Thanks for such a great tutorial.
Hi,
I am also facing same problem while using php SDK api for facebook connect on my website .
Error is as follows:
An error occurred with PHP SDK Unit Tests. Please try again later.
Please help me
hi,
I’m try to use facebook to login to my site, which i can but my problem is that i need to get these details.
Email, first name, last name, location, education, work history, gender, relationship_status.
Using PHP can this be done as i only can get email, last name, first name.
Please let me know if i can get all these details .
Thank you,
Majid
Hi,
I found your tutorial is quite clear but when I try to use your demo codes on my webserver but i got the error below.
FacebookApiException Object
(
[result:protected] => Array
(
[error_code] => 77
[error] => Array
(
[message] => error setting certificate verify locations:
CAfile: /usr/local/share/certs/ca-root-nss.crt
CApath: none
[type] => CurlException
)
)
May I know is there any problem is my server configuration? Thanks in advance!
Hi, any solutions to this by any chance. I am experiencing the same problem. Thanks.
Woah!… Many thanks! This really helps….
Hi, I’m creating a website in php where users can login to their facebook accounts and can post to their fan page wall.
One of the step in the authentication is to add the facebook app with the fan page. i have the permanent session key, uid, page id etc. Please guide me how to add page with app.
Thanks in advance.
Baljeet
Hi, I’m creating a website in php where users can login to their facebook accounts and can post to their fan page wall.
One of the step in the authentication is to add the facebook app with the fan page. i have the permanent session key, uid, page id etc. Please guide me how to add page with app.
Thanks in advance.
Baljeet
YOU MADE MY DAY!!! THANKS A LOT!
I am using the $fbme = $facebook->api(‘/me’); code and I never get anything in return.
What do you think is the root cause for this since everyone uses this for their examples.???
Well looking into this issue, I think it is not allowed by my hosting site…
Hi
i need to get email of the customer ,
i followed your code , but i can’t get email ,
kindly help me.
http://173.203.104.63/football/logins/
Thanks,
Vinoth.M
Please provide email permission in the authentication process, so that you could retrieve user’s email address using facebook api.
Hai Mahmud,
Thanks for your valuable replies , Now i get user email address and his other basic details.
Now i need to track his friends list and also track his wall and also i need to invite .
Kindly help me…
Thanks & Regards,
Vinoth.M
I am attempting to create a Fan Page within facebook, is this the tutorial I need to create an application?
Within the application I simply need to grab a visitor/user of the fan page’s UserId from Facebook. Is this the tutorial for me?
Please, excuse me being such a newb
You can see the files here http://facebook.makepixels.com/files.txt
It´s txt file
If someone has one that will operate normally, please you can send me I really appreciate so much. my email is
——
soporte@makepixels.com
—
I can add to your messenger
Thanks again.
Please describe about your problem.
Hi
Looking for a basic Facebook Application Code in PHP.
Came across you Javascript tutorial and then this PHP one. I haven’t read it yet but it seems it would be easy implementing it.
I have faced a issue here, I clicked on your demo URL -
http://thinkdiff.net/demo/newfbconnect1/php/index.php
but when the page opens, i have given the access permissions and then it loads again and again i.e. refreshing again and again.
I’ve just checked and found no problem that you’re saying.
Hi tried the code mentioned above and got this error.
===========
Application temporarily unavailable
Parse errors:
FBML Error (line 7): illegal tag “body” under “fb:canvas”
Sorry, the application you were using is experiencing a problem. Please try again later.
===========
Please tell how to proceed for it???
The error says don’t use html tag. So avoid it.
hi Mahmud,
thank you a lot for the tutorial ,it is great!
One question: i included the news feed from facebook (the first page you see when you login ) but that doesn’t show for example that USer B is now friends with User C. do you know how to show that?
I did this to show the news feed:
try {
$newsfeed = $facebook->api(‘/me/home’);
}
catch(Exception $o){
d($o);
}
I do get the rest! tHank you very much!
Thanks for your nice tutorial. I have created a script which update status of fb-page and is working exactly as per desire. The Only problem is that the content posted via this script is only viewable to admin of that page, for other user cant!!! any solution?
Access Token Link:
https://graph.facebook.com/oauth/authorize?type=user_agent&client_id=xxxx&redirect_uri=http%3A%2F%2Fwww.myurl.com/atok.php?return=true&scope=user_photos,email,user_birthday,user_online_presence
Update status link:
https://api.facebook.com/method/stream.publish?message=“+opener.document.fstat.status.value+”&target_id=yyyyyy&access_token=returned_accesstoken&format=json
Just to let you know you saved me lot of time.
Many thanks!
I am in the process of programming a custom CMS that will implement connection with various social media platforms. I found this to be a very nice primer to the Facebook graph API. Thanks for the info!
You’re Welcome.
Thanks for the tutorial!
I only don’t know and understand how to custom the output content.
Right now I’m getting all the content into an array as:
Array
(
[location] => Array
(
[id] => 115351105145884
[name] => Cairo, Egypt
)
)
But I don’t want it to be in array …
how can I custom the output please?
For example I want something like this:
$location['id']
$location['name']
I just wanted to post cause this was so helpful for me. In my PHP file I had some mysql code and for the life of me I couldn’t figure out why I was getting 2 sets of the same data getting inserted into my database each time the file would load. I found out it has to do with this line -
FB.init({appId: ”, status: true, cookie: true, xfbml: true});
I added this and it fixed it – session : ,
I’m assuming it wasn’t finding the session so it would load the the page twice.
My post above got butchered from html. This is what I meant with not safe characters removed.
FB.init({appId: ‘?=$fbconfig['appid' ]?’, status: true, cookie: true, xfbml: true});
session : php echo json_encode($session);
Great work Mahmud!! .. this really helped me !
Hey Mahmud, thanks! Do you know how put a newline (Enter) in the description (of a post to a users feed)?
I too want to know this.
Has anyone found a fix for the IE login window bug?
IE opens the popup, but after you enter username and password the popup just hangs there with a white screen.
Is is possible that i get facebook’s feed through graph APIs, as it is shown when we clicked this link https://graph.facebook.com/me/feed?access_token=…
hye.
i got a problem here. Could you help me?
This code has been shown when i try to connect through the login button. It’s actually long codes.
Thank you.
FacebookApiException Object
(
[result:protected] => Array
(
[error_code] => 1
[error] => Array
(
[message] => Protocol https not supported or disabled in libcurl
[type] => CurlException
)
)
Hello,
i want to change profile picture through my application.as u did update the status through ur application.
kindllly help me
Ammara,
We can not change our Profile Image thorugh Graph or Javascript APi.
By far the best facebook apps tutorial.
There is a way to avoid HTTPS in a free Hosting like 000webhost?…i got “Protocol https not supported or disabled in libcurl” exception…i think is SSL problem.any help? or how i can create and aplication for test purpose,in my own local server (localhost) ???
Great work Done Sir
i was looking for this thing nd finally i got it
thanku So much for posting such a great post
@Ammara.
Upload a Picture on Profile or in an Album.
————————————————-
Please keep in mind that you could only upload photos in your profile or your albums via application. A typical scenario of this would be, you’ve a website where people are logged in via facebook connect. In that site there are many photos and your user may wants to upload some of photos in his facebook album.
When you’ll create $facebook object then set ‘fileupload’ => true
$facebook = new Facebook(array(
‘appId’ => $fbconfig['appid'],
‘secret’ => $fbconfig['secret'],
‘cookie’ => true,
‘fileUpload’ => true
));
Use below code, if you provide album id then the photo will be uploading in corresponding album otherwise the application will create an album and will upload photos on that. Please remember, ‘source’ should be absolute file path not be any url. And you must have to provide the ‘@’ symbol before filename. Suppose your php code is in /var/www/ folder and the image file is also in /var/www/ folder. Then just use source => ‘@filename.jpg’
$albumID = isset($_REQUEST['albumid']) ? $_REQUEST['albumid'] : ‘me’;
try {
$uploadstatus = $facebook->api(“/$albumID/photos”, ‘post’,
array(
‘source’ => ‘@FILENAME’,
‘message’ => ‘Messsage’
)
);
} catch (FacebookApiException $e) {
print_r($o);
}
ohh Great !!! This is better than facebook’s own documentation. I like it Boss. Thanks.
Nice post, great detail. I would have liked to see the costs that are associated to it so I could add to my business case justifi cations to use the technology. Keep up the good work! Great Job!!! Informative and attention keeping!
facebook connect applications
Hi, I’m redesigning my site and i will include facebook comments on my wordpress instead of the normal comments.
I am looking for a way to get the postcount from my facebook comments on my index page but can’t find how.
I’ve looked everywhere and stumbled on this site. By the looks of it, you guys know a lot more from programming than I do
Can someone help me? or lead me in the right direction?
thanks for sharing dude,
i like this so much,
great tutorial,
Thanks for your demo, I’m a new bee to PHP and facebook development so i find a very hard time to get started ..
Your code is simple and understandable BUT
For unknown reason to me any graph api call doesnt return anything
meaning i included facebook.php ( the latest PHP sdk ), checked that JSON and cURL are enabled on my server and yet its functions dont return anything at all !!!!
Just a facebook canvas blank page !!! any idea why is that may be i miss something
Hi, iam getting the following error when i click on the facebook login icon:
API Error code: 191
The specified url is not owned by the application
redirect_uri is not owned by the application
What could be the problem…. ?
Well Iyar this msg error when I didn’t assign the correct callback URL
You should be careful when putting ur callback URL that points to the application on yr server
Http://www.domain name.com/folder name/
I hope that works with u
May be facebook’s recent change. I will check it later.
Great work, I’m very excited about the future of Facebook Open Graph and the web!
would you help me how do I invite friends using FB Connect??????? I worked but its not properly functional..
I tried to use the php sdk example as is, and it works.
I tried to just change this line in example.php
$loginUrl = $facebook->getLoginUrl();
to
$loginUrl = $facebook->getLoginUrl(array(‘req_perms’ => ‘email,read_stream’));
but it seems that nothing changes, facebook doesn’t ask me additional permissions for email and read_stream, and
print out just the public info.
Did I make a mistake?
Thanks for the post!
Hi,
Does anyon 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