Facebook has announced and released a new PHP SDK to use on the platform, making significant changes to the way developers can access the API and the new Graph API 2.0. The new PHP SDK splits the functions into multiple classes, so you only need to include the classes you need.
Basic Example
In essence, making API calls and getting data has changed significantly. Just look at the sample code below which asks the user to login and prints their profile data:
You now need to include each individual class you require (require_once
), set the namespace alias (use
) and then calling the functions you need to achieve login and retrieval of API response.
Chaining
The good thing is that the code can be reduced from the example above using chaining. From the example above, you can turn lines 92-95 into just one (large) line. Take this example:
The new SDK will definitely take a while to get used to. In fact, the new documentation already has a few errors in it that makes it difficult to even get started…
Additional Permissions / Scope
If your application needs additional permissions from the user, you can pass these in as an array to the $helper->getLoginUrl()
function. The first parameter takes an array of permissions like the example below:
Note: The Facebook PHP SDK 4.0.0 contains more classes than used in the example above, but I’ve included the minimum number needed to achieve login and retrieval of profile information.
Logout Page
For those asking about how to log a user out from your application, you must clear the session or delete any cookies you set. In my example, the following is required on the logout.php
page to clear the user’s session.
Update #1
8th May 2014: The original code in this post has been updated to include session management. The new code now remembers any saved access_tokens, validates the token and makes an API call without asking the user to login again. The code works for the changes included in Facebook PHP SDK v4.0.1 and v4.0.2. The new code also includes an extra line to generate the logout link for the user.
You can see the changes to the code here.
Update #2
21st May 2014: Facebook has yet again updated the Facebook PHP SDK, this time to version v4.0.5. The new changes are significant, adding a number of new files that are required for the Facebook SDK to work. I’ve updated my sample code yet again to account for these changes.
You can see the changes to the code here.
27th May 2014: Newly released version v4.0.6 continues to work with the above sample code.
Update #3
10th June 2014: Facebook has updated the PHP SDK to version v4.0.8. The new changes mode some of the classes into a sub-folder, breaking existing code. The below snipped shows how the class includes and use
statements needs to be changes:
11th June 2014: New tutorial on how to create Facebook Tab Apps has been added. Required Facebook PHP SDK 4.0.7 or later.
Update #4
27th June 2014: I’ve made a change to the initial code to deal with session errors. Essentially, I’ve changed the first <code>IF…ELSE</code> statement into two separate <code>IF</code> statements to deal with session errors, like expired sessions. You can see the changes separately here.
Facebook has also made further changes to the SDK but failed to tag the new version as v4.0.9. Therefore my modifications in Update 3 has been updated to include the further file changes in the same version (v4.0.8). You can see the modifications separately here.
Update #5
27th October 2014: Added logout.php
code due to multiple requests.
Hi Niraj Shah,
Thank you so much for the article,
I’am integrate version 4.0.9 into my site.
You could help me how to show popup log in.
Currently, When click log in, it auto redirect to facebook site.
Thanks you so much.
Dan.
The Facebook PHP SDK uses a full-page login. You need to use the JavaScript SDK if you want a login popup.
Thank you.
I’ve just fixed by use JavaScript SDK.
thank again.
Dan.
I added ‘&display=popup’ at the end of the getLoginUrl and it changed the display mode to popup
i got blank page using this code please help me
validate() ) {
$session = null;
}
} catch ( Exception $e ) {
// catch any exceptions
$session = null;
}
}
if ( !isset( $session ) || $session === null ) {
// no session exists
try {
$session = $helper->getSessionFromRedirect();
} catch( FacebookRequestException $ex ) {
// When Facebook returns an error
// handle this better in production code
print_r( $ex );
} catch( Exception $ex ) {
// When validation fails or other local issues
// handle this better in production code
print_r( $ex );
}
}
// see if we have a session
if ( isset( $session ) ) {
// save the session
$_SESSION[‘fb_token’] = $session->getToken();
// create a session using saved token or the new one we generated at login
$session = new FacebookSession( $session->getToken() );
// graph api request for user data
$request = new FacebookRequest( $session, ‘GET’, ‘/me’ );
$response = $request->execute();
// get response
$graphObject = $response->getGraphObject()->asArray();
// print profile data
echo ” . print_r( $graphObject, 1 ) . ”;
// print logout url using session and redirect_uri (logout.php page should destroy the session)
echo ‘<a href=”‘ . getLogoutUrl( $session, ” ) . ‘”>Logout</a>’;
} else {
// show login url
echo ‘<a href=”‘ . getLoginUrl( array( ’email’, ‘user_friends’ ) ) . ‘”>Login</a>’;
} ?>
You clearly haven’t copied my sample code correctly. You probably have a few PHP errors in there causing a blank page. Enable error output and fix the errors.
how to enable errors in heroku
The same way you enable errors in PHP:
I just get a Login link and nothing happens when I click on it. I am new to FB development. Can you help me? I am trying to create a Canvas app.
sir i copied ur code but the problem comes in it that once i logged in and then logout it still shows the logout link and my profile data instead of showing login link ..
Are you destroying the session and deleting cookies on the logout page? If you don’t clear the session, the user will still appear logged in until the session expires.
you really made my day,
Thanks a lot, facebook official tutorial sucks
I have the 4.0.8 sdk version.
I installed 2 days back using composer and using the autoload.php.
So I dont need the require files.
My problem is that the session isnt being stored.
it is redirected to the login page and says: Undefined variable: http_response_header in C:\wamp\www\facebook\vendor\facebook\php-sdk-v4\src\Facebook\HttpClients\FacebookStream.php on line 75
I am stuck. Please help
What version of PHP are you using? Also, what code are you using to call the API. This error would occur if you’re trying to access a page that’s restricted or not found.
Hello. I am a novice at coding. Currently trying to create a facebook app. I followed your tutorial and I managed to get the login and then the pop up box that asks for permission. But after clicking okay, nothing happens – shows the broken page with the sad face. When refreshed, the pop up box no longer appears. No user details are shown either. I am so confused. Can anyone help me out? Thanks.
Once the user has authorized your app, they will never see the login popup again (unless you change the scope of permissions). Are you using the most recent code I’ve posted, as it includes fixes for the blank page issue. Also, make sure you’ve updated any URLs I’ve used in my code to match your setup. It’s likely that my
sites.local
URL is causing a problem on your setup.Thank you so much for replying… I am not too sure but I think it’s because I am using localhost and facebook doesn’t like that – requires a security certificate. I tried to create my own self signed one using openssl within xampp but it doesn’t seem to load anything either. Do you have any idea how to use localhost to implement a facebook app? I would really appreciate any help or advice. I feel so lost – blindly trying to solve it. (Not even sure if it’s meant to be this complicated or am I just stupid)… thanks again.
Facebook used to allow developers to test apps without SSL, but now it’s forced. You’ll have to setup a self-signed certificate to test locally, or code on a server with a valid SSL certificate. I use MAMP on Mac, with a self-signed certificate to develop locally.
IT FINALLY SHOWS SOMETHING. THE DATA RETRIEVED ON THE PAGE! Does that mean I have combated the ssl problem? 😀
I have just redone it all again. Copied your code. For the redirect link so I put the facebook url? https://apps.facebook.com/myapp
I get this error now: Fatal error: Class ‘Facebook\FacebookServerException’ not found in C:\xampp\htdocs\app\Facebook\FacebookRequestException.php on line 110
How do I know which facebook files to include, there is so many? I copied your code..
Thank you!
Include the following below the FacebookSDKException line:
Then further down, add:
Thank you so much! I think it’s finally working now, data echoes onto the page, woo!
Can I ask about the logout.php, how do we log out the user?
Thanks!
logout.php
should contain code to destroy the session and a redirect back to your app / site:I had following error :: PHP Fatal error: Class ‘Facebook\\Entities\\AccessToken’ not found in /home/madawa/Desktop/F/Facebook/FacebookSession.php on line 74, referer: http://localhost/F/Test.php
Use the code from Update #3 to fix the issue.
Looks like they are up to 4.0.9, I wonder how much further they will go?
They are currently working on v4.1, which is probably still a few weeks away from release. The SDK is undergoing major changes, so this tutorial is pretty much be useless when v4.1 comes out.
Actually it’s been a good learning experience. Ironically we’ll all have to wipe out what we’ve done but thats part of the process. Hopefully it’ll be worth it in the end.
I just wanted to say,…. THANKYOU SO MUCH!
Hello,
When I open your example then it shows a Login link. I can then sign into facebook, but then afterwards I am redirected to an empty page on localhost showing the start page of my xampp server. Any idea what I have done wrong?
Check the redirect URLs you are using in your code. Make sure they are valid and pointing to the correct code on your server. It’s probably one URL that you’ve forgot to change somewhere in the code.
Fatal error: Call to undefined function Facebook\Entities\mb_strlen() in …../Facebook/Entities/SignedRequest.php on line 301
I got this error please give me solution….
Looks like the
mb_strlen()
function isn’t installed on your version of PHP. See the PHP Manual for information on how to install it.I just learn this SDK, want to make some piece of script in my Apps. Thank you for this tutorial.
Hi all,
If I have the username/password of the user that uses the app, can I do the login process autmatically?
No, Facebook only supports OAuth authentication for the API. There are some instances where this is allowed (i.e. PlayStation Network) but it’s not available to the general public. You should not collect usernames / passwords of users, except your own.
So it looks like the older 4.x.x SDKs could be shut off in December. When I visit https://developers.facebook.com/ there is a notice that says:
“Graph API v2.0 and the new Facebook Login. Upgrade your apps before December 25 to protect 90% of your users’ experiences.”
This is just a precaution and only affects apps that still use the v1.0 Graph API. You can continue to use the older SDKs (PHP v3.x) until April 30th 2015, and even longer as long they use Graph API v2.0.
The PHP SDK 4.x is not affected as it already uses Graph API v2.0, but PHP SDK 4.1+ will include new features going forward.
is giving PHP Fatal error: Class ‘Facebook\Entities\AccessToken
show how to solve this issue .
Read all the updates at the bottom of the post for updated code.
[…] has released an official PHP SDK, similar to the Facebook PHP SDK 4.0. As usual, it’s not very well documented and you may have to jump between different […]
When you load the page, is it meant to show the login URL even when you are already logged in on facebook? I also get this error: Catchable fatal error: Argument 1 passed to Facebook\FacebookRequest::__construct() must be an instance of Facebook\FacebookSession, null given, called in.. kinda confused now that I have different scripts.. I have one script (getfriend.php) that includes all your code above and get friend request. Then another script that holds the html of the page which includes the other script… I have other scripts too that includes “getfriend.php”… I have the html in a different script because I don’t want this to be repeated in other scripts :S
The login link will only be shown if the session does not already exist and a logged-in user isn’t detected from the session. Depending on your PHP Session settings, this is usually after a hour. The error you’re getting suggests you are trying to pass in an invalid session to the FacebookRequest class, which suggests that the user isn’t logged in.
I think I know why I am getting the error… but not sure how to correct it. Hard to come up with a good design for your code. Too much going on, kinda confusing. hmm. Is possible to do direct to another page when user has clicked on the login URL? Would I use header for this?
I think I’ve fixed it using header and adding another script! So I don’t include the script that makes the api request in index until I have got the session… so I don’t get the error. 🙂 think it works. 🙂 thanks!
What I don’t understand is, it works fine on my localhost url but when it is loading from the facebook canvas, the buttons isn’t responsive – nothing works. Do you have any idea why this is the case?
Add target=”_top” to the login link for Canvas Apps. Facebook doesn’t allow navigation of other FB paves via iFrame.
I think it worked before…. and my notification link, the buttons work and directs me to another page..
Do you mean, like this?:
} else {
// show login url
echo ‘getLoginUrl( array( ’email’, ‘user_friends’, ‘publish_actions’, ‘publish_stream’, ‘manage_friendlists’, ‘user_photos’, ‘read_friendlists’ ) ) . ‘”>Login’; //get permissions
}
I get the error that the requested URL is not found.. my redirect url is the canvas URL…
// login helper with redirect_uri
$helper = new FacebookRedirectLoginHelper( ‘https://apps.facebook.com/myapp’ );
Your code appears garbled. Try wrapping your code in <code> tags next time.
I think the problem is with the browser? It has a warning sign saying it’s not secure as it contains images when I click the submit. So when I disable the blocking, it seems to work again.
This is probably caused by your code including images or CSS / JS files over a non-SSL / HTTPS connection. Make sure any files your reference are loaded using HTTPS.
Kinda confused. I don’t actually have any images or CSS/JS files. Just the multi part form to upload a photo onto the server.. also, I have a SSL connection? (I created the self signed certificate??) otherwise, the page wouldn’t load at all on facebook… (right? Sorry, not even sure)
Also, have you tried out the privacy parameter when posting? I have been stuck on this for 2 weeks, and cannot seem to find anyone who has been stuck on the same thing to find an answer. Do you think you could have a look at my sof question?
http://stackoverflow.com/questions/25084519/facebook-api-php-setting-privacy-of-photo-post-to-custom-but-shows-only-me-i
Friend id – I got from GET /me/friends – which is the unique user id of those who have accepted my app. I have tried both deny and allow but whatever user id I put, it just result in “only me”. I have put “ALL_FRIENDS” for allow and it works – just id not working! I must be missing something stupid again or has this somehow been changed/deprecated by facebook? 🙁 sorry for such a long post.
First of all, this is a very good tutorial, but i have a question. When I click Login from the index.php , it redirects me to facebook to enter my user and password, then it shows me the data it fetches. So far, so good, but when clicking Logout, it doesn’t destroy the session and redirects the user to the index and still show the data, not the login button. Can you tell what should I do? For the logout.php I used your code from the comments.
Do you have
session_destroy();
in yourlogout.php
script? That’s the most important like to delete the user’s sessions.I click Logout, it goes to logout.php, then I redirects to index.php where I have the Login button and nothing more, but instead of showing me Login button, it shows me the facebook data with the Logout button.
I too had this problem – my logout page redirected to my app, which showed all the user profile data. It looks like you also have to delete the cookies and any globals associated with the Session. See here for code that worked great:
http://php.net/manual/en/function.session-destroy.php
Thanks a lot Brian, it worked. 🙂 Also, thanks to Niraj Shah for the tutorial.
I just wanted to say that this tutorial was Massively helplful, after a weekend of banging my head against the wall trying to get login to work, when so many web pages are written for older versions of the SDK. Kudos to you for good, current, working code!
I have a script that retrieved the picture from posts. now the picture field is not there since a few days back!? Do you know how to get a picture in a post in some news feed?
Must be a bug, but it appears to work for me. Try searching for any related bugs that may have been reported.
Which group did u test in? If I check in the Graph API Explorer,
groupId/feed
i see all posts. And just a few days ago, it was a picture field, in the posts that had a picture. Now I only see this field in shared posts.
Yes, it looks like it’s no longer working. It must be a bug with Facebook.
I found bugreports on it, as you hinted.
https://developers.facebook.com/bugs
Its a fix already on
https://graph.beta.facebook.com/
That works. Thanks for pointing this out. FB have quite a good bug reporting tool here.
I was looking to some codes for managing the session; and this is working like a charm. Keep up the good work.
sir, how to make if else statement on condition by which notification to fb friend is successfully gone or not..?
I was having the error “Session has expired, or is not valid for this app” and it was because I change ” array( ’email’, ‘user_friends’ ) ” to ” array( ‘public_profile’ ) “. Avoid doing that, public_profile in the new sdk is always asked by default, if you only want that and no other permission just use “array()”.
Hello. It’s possible to make a facebook comment box like this https://developers.facebook.com/docs/plugins/comments/ in php?
I didn’t find anything about it on facebook tutorials.
Yes it is possible to replicate this functionality in PHP but it’s a waste of time. You won’t find any tutorials on it because it’s easier to just use the plugin or something like disqus instead of trying to re-invent the wheel.
I want to sort that facebook comments by likes. And i was thinking that it’s possible if only i make in php that comment box. I’m beginner and i’m still learning. Can you help me with some advices?
Even with PHP, it will be difficult to achieve this as the API does not support sorting. I am unable to provide specific help as this is a complicated process, but I do offer paid consulting services.
Awesome tutorial…… but 1 issue is that when i click on logout button session is not destroyed. I also destroy session in logout page but nothing happens. Any help?
Is the user logged out of Facebook successfully?
No, user can’t logged out of facebook…… i also destroy session on logout page.
Not sure what could be going wrong then. If the correct session is used in the logout API call, the user should be logged out of Facebook. Then it’s your responsibility to delete the cookie / session and log them out if your App.
Thanks for your rply…… I will be very thankful to you if u help me in log out code. This is my code
I’ve added the code used in my logout page in the main article.
Thanks for your reply…… one more issue is that your logout line which redirects to logout.php didn’t work correctly. When i click on the logout link it redirects to facebook home page. I also edit my log out url on that page but it redirects to facebook home page.
Hi,
I did everything but I got white screen. 🙁
please help.
Double check your app settings on Facebook and make sure you are using the correct App ID and Secret in your app. Add some debug code to your app to see if any Exceptions are thrown anywhere that could be causing a blank page.
Hi Niraj,
Need to integrate facebook php sdk 4.0 in my local. I have used basic example from this site and implemented in local. I can able to view my login user detail, but when i am trying to get user friends, it is not fetching the friends content. it only displaying total count.
$request = new FacebookRequest( $session, ‘GET’, ‘/me/friends’ );
Please guide me to resolve this issue..
Thanks..
In order to get friends information, you must ask for the
user_friends
permission. This new permission only allows you to see mutual friends that also use your application. You can no longer see the entire friends list unless you use thetaggable_friends
API.Hi,
I am using the below code to authenticate the user with facebook login app: i have a problem the code below is working fine under certain scenarios.
a) User A Logs in with fb account works fine – > logs out ->works fine
b) return to login page after USER A is logged out
c) USER B logs in with second account the graph returns the USER A’s Details instead of the USER B
d) if we open the facebook on the next tab logged in user is USER A.
Im not sure where i am going wrong or if it is the SDK acting crazy!.
When you log the user out of Facebook, you also need to make sure you clear the session for that user in your code. Otherwise, the access token is stored in the app, and a second user logging in will inherit the first user’s session. Use
session_destroy()
or equivalent to clear the session.Hey Niraj,
I am wandering how to get the list of all the friends of the authenticated user and groups he joined ?
kindly reply me soon..
thanks
To get Friends, please see this tutorial. For groups, you’ll need to ask the user for the
user_groups
permissions and make a API call to/me/groups
.The script works fine and it’s the most complete, useful version that I’ve found (and, as far as I could find, the only one that truly works with php sessions). However, my problem is that when I click Logout, it logs me out of FACEBOOK, not just the app itself. Is that normal? I would expect to logout of the app, not off of facebook…
Yes, making a API call to the logout method in the Facebook SDK logs the user out of Facebook. To log the user out of your application, you must delete the cookies / session related to that user. I’ve included code for my
logout.php
page at the end of the article.Hi,mister Niraj.
I’m now trying to using Facebook php sdk 4.0 to retrieve datas of my facebook acount.
I tried , but php always says (apache error log) class SDKException not found and session is not active.
Here are source codes of two files(call , and callback pages)
call.php
<?php
session_start();
require("vendor/autoload.php");
use FacebookFacebookRequest;
use FacebookGraphUser;
use FacebookFacebookRequestException;
use FacebookFacebookCanvasLoginHelper;
use FacebookFacebookRedirectLoginHelper;
use FacebookFacebookSession;
use FacebookFacebookSDKException;
use FacebookHttpClientsFacebookHttpable;
use FacebookHttpClientsFacebookCurl;
use FacebookHttpClientsFacebookCurlHttpClient;
use FacebookEntitiesAccessToken;
use FacebookEntitiesSignedRequest;
$iti=new FacebookSDKException;
FacebookSession::setDefaultApplication('xxx','yyy');
$page_id="655095094605502";
$helper = new FacebookRedirectLoginHelper('http://ec2-54-64-18-188.ap-northeast-1.compute.amazonaws.com/faceb/callback.php');
echo 'getLoginUrl() . ‘”>Login with facebook‘;
callback.php
getSessionFromRedirect();
echo $session;
} catch(FacebookRequestException $ex) {
// When Facebook returns an error
echo $ex->getMessage();
echo “ai”;
} catch(Exception $ex) {
// When validation fails or other local issues
echo $ex->getMessage();
echo “hi”;
}
if(isset($session)){
$request= new FacebookRequest($session,’GET’,’/me’);
$response = $request->execute();
$graphObject = $response->getGraphObject();
var_dump($graphObject);
} else{
echo ‘getLoginUrl() . ‘”>Login with facebook‘;
}
$access_token=( new FacebookRequest($session,’GET’, ‘/’ . $page_id, array( ‘fields’ => ‘access_token’ ) ))->execute()->getGraphObject()->asArray();
// save access token in variable for later use
$access_token = $access_token[‘access_token’];
$page_post=(new FacebookRequest($session,’POST’,’/’. $page_id .’/feed’, array(
‘access_token’ => $access_token,
‘name’ => ‘Facebook API: Posting As A Page using Graph API v2.x and PHP SDK 4.0.x’,
‘link’ => ‘http://ec2-54-64-18-188.ap-northeast-1.compute.amazonaws.com/faceb/call.php’,
‘picture’ => ‘http://ec2-54-64-18-188.ap-northeast-1.compute.amazonaws.com/tokub/image1.jpg’,
‘caption’ => ‘The Facebook API lets you post to Pages you administrate via the API. This tutorial shows you how to achieve this using the Facebook PHP SDK v4.0.x and Graph API 2.x.’,
‘message’ => ‘Check out my new blog post!’,
) ))->execute()->getGraphObject()->asArray();
// return post_id
print_r( $page_post );
?>
I ‘m sorry to flood your blog with much source code,and paste confidentials.But I absolutely must finish my work until tomorrow morning.Can you say anything about my codes?
First off, remove the line
$iti=new FacebookSDKException;
. It’s not required. Second, add try…catch statements around the Facebook API calls so you can see where the error is coming from.hi tatsuyo – did u manage to get this sorted. i see that u r working on aws. i am having heaps of hurdles getting this to work .. could you help.
Hi Niraj
But i can not get user’s country i mean location or friendlist i just get friends total count.
I cannot help you without source code or the query you’re using. Post a question on Stackoverflow and send me the link.
Why I can’t go to the next process (line 84 process) after login ? I always back to the login link
Are you getting any errors or exceptions with logging in?
No, I’m not getting any errors…
But when I open it from the Firefox browser, I’m getting error message: couldn’t connect to host
Then it means your ISP is blocking connections to Facebook, which could be the reason for the error.
I am facing an issue in asking permission to enduser for my facebook app as written in code i had ask manage page permission (manage_page) in scope parameter but I am getting blank data. can some body help me..
this is the code i am using
$loginUrl = $facebook->getLoginUrl(array(
‘scope’=>’publish_actions,manage_pages’
));
The issue is the your
$loginUrl
. Change your code to:i.e. You don’t need
scope
in the array. And the permissions are an array. It’s different to what you would have used in the old PHP SDK.Hi there, great example! I have a couple of questions though. I’m able to get your example working fine. I see my profile data. I’m incorporating this into a wordpress plugin that I am trying to write. There are some changes that I want.
For example, I want to have my plugin automatically login (i don’t want there to be the need to click Login. Perhaps maybe clicking it once would be ok, but then beyond that I’d like the neccessary info to be stored into wordpress).
Next I want to grab the current users feed in json format. I’ll parse this feed and import it into a database.
I want to display the feed on my website along with a feed of my twitter and instagram posts which were quite easy to deal with the api of those systems.
So a couple of questions, do i need the authentication part if i only want a public user feed?
Is there a way to automate the login in facebook approved way?
How can i get my user feed?
I had tried this, but it comes back blank.
// graph api request for user data
$request = new FacebookRequest(
$session,
‘GET’,
‘/me/feed’
);
$response = $request->execute();
// get response
$graphObject = $response->getGraphObject()->asArray();
In order to get the user’s feed, you need to ask for the “read_stream” permission. Facebook also need to approve the user of this permission before it will work for users. You can get public feed information without asking for permission. As for login, you should always ask the user to Login – otherwise it could be classed as “forcing” the user, which Facebook doesn’t like.
How to get the person first name last name in your given app code. I have to fetch the erson name and image as well.
Have a look at the
$graphObject
variable on line 95. All you need to do is:Hi Niraj,
Great post. It gave me a very good start.
I am fetching the uploaded photos of a user using
$request = new FacebookRequest( $session, ‘GET’, ‘/me/photos/uploaded?limit=9’ );
and setting the limit to 9, can you please tell me how I can implement the next and previous buttons that it just refreshes the results only.
Thanks in advance.. 🙂
Mayank
At the bottom of the response, you’ll see the ‘paging’ object. You can use the ‘next’ and ‘previous’ URLs to handle the pagination by making a new API call to each.
Can you please guide how I can make the API calls to the next and previous URLs.
Have a look at the response and you’ll see it. All you need to do is call the URL it gives you. Not that difficult to do yourself.
chaining – u may want to correct – lines 91-96 not 41-44
Thanks for pointing that out. The lines had changed after each update!
Hi Niraj – very good article from the ones I have searched on the same topic. As I am a novice at all this I am facing some issues, from what I read along these comments some of these issues seem familiar (blank page).
One of them is that SSL is required and you have said – “I use MAMP on Mac, with a self-signed certificate to develop locally.” Does that mean I need to enable SSL on my web server – i found this article at https://beeznest.wordpress.com/2008/04/25/how-to-configure-https-on-apache-2/ .. is this what I have to do.
Acc to this link, looks like I need a domain name (am i right) – is there a way I can proceed without a domain name – would you be able to suggest any directions or links. Thanks!
On my localhost, I setup the domain http://sites.local using MAMP. MAMP Pro has a setting that lets you setup SSL on any domain, so I set it up to use that domain – there’s even an option to create a self-signed certification to use.
The tutorial should be helpful – all you need to use is setup any domain you want and make sure the /etc/hosts file is setup correctly so it points to localhost.
I am using Amazon AWS Linux. So, trying to figure if what the above link explains (ie. setup SSL on Apache) is what I should be doing.
AWS will be using either httdp or Apache 2 as the web server. The steps should work for either one, although the locations of the config files will be different with each version.
Great Article.Save my time to update facebook sdk upgrade.
you don’t need bunch of require_once(..) statements if you start a session before you use “use” statements
This is true if you use Composer as the classes are auto-loaded, but not if you want to use the SDK as stand-alone. If you don’t include the
require_once
statements, you’ll get a bunch of “Class ‘Facebook\FacebookSession’ not found” errors. Those errors will occur regardless of where you start the session.I believe I used the SDK as it is.
I’m not so sure about “Composer” but since I’ve never installed anything like it and removed composer.json file from the source I doubt that “Composer” is a matter.
It still works like a charm with out it. Or am I accidentally using “Composer”??
Let me know if i’m wrong.
I’m not sure. Email me your sample code and if it works, I’ll updated my tutorial and credit you for the findings.
This is the only difference I see right after session_start();
// Skip these two lines if you’re using Composer
define(‘FACEBOOK_SDK_V4_SRC_DIR’, __DIR__ . ‘/sdk/src/Facebook/’);
require __DIR__ . ‘/sdk/autoload.php’;
I guess these two lines won’t be needed if you use composer as the comment says..
I looked into that autoload.php file
yea it requires bunch of files needed eventually. so basically it’s doing the same thing.
Yes, the
autoload.php
file makes it easier to include the files from the SDK. That would explain why you don’t need therequire_once
statements.hi,
i want to add multiple Facebook accounts at a same time.(like Google can add multiple account and also we can access that accounts separately.)i also want to add Facebook page and group.for that i want when i will click on connect page then it will connect only page and also give option for choosing profile and group .using php .Please reply .
Nothing something you can do with the API and SDK unfortunately. The multiple login with Google is built into Google itself, and accounts for the fact that a user can have multiple gmail accounts (e.g. a personal one and Google Apps / Business one). With Facebook, it’s assumed that a user will only have one account (personal) so there is no built-in option to handle multiple login scenarios.
thanks niraj
I want to thank you for keeping up to date on this. 🙂
[…] how the new version works. This is the first major update to the SDK since it was released in May 2014, and one that has been mostly lead by the open-source […]
Hello Niraj, can i get your opinion on this question http://stackoverflow.com/questions/28626393/best-way-to-tracking-user-status-under-tab
Are you taking about authenticating the user across multiple pages (not sure if this is what you mean by status)? If so, the best way to achieve this is using PHP $_SESSION or cookies. Cookies would be your best bet here – the only thing you need in the cookie is the user’s access_token, which can be used to authenticate the user across the various pages.
Dear Niraj,
apologies for the late answer. I just wanted to say thanks, have been following you for a quite some time and your opinion means a lot to me. I’ve thought that those sessions were right solution, but when expert says that it should be done with cookies, than I’ll do it in that way and follow performances of the app.
Once more, thank you Niraj very much!