Tutorial: Integrate Facebook Connect to your website using PHP SDK v.3.x.x which uses Graph API
Now-a-days it is common for websites to have Facebook Connect integrated to it. Facebook Connect is the iteration of Facebook Platform that allows users to ‘connect’ their Facebook identity, friends and privacy to any site. It enables a website to implement features of Facebook platform on it. Facebook Connect has been around since May 2008. Since then, Facebook has released various Software development kits (SDK) namely JavaScript SDK, PHP SDK, iOS SDK (iPhone & iPad) and Android SDK for easy implementation of their API. In this tutorial we will be concentrating on PHP SDK. As of today, the latest version of PHP SDK is 3.1.1 which was released on August 10, 2011. PHP SDK v3.x.x is a major update from v2.2.x, as the new SDK uses OAuth authentication flows instead of Facebook’s legacy authentication flow. The new SDK has two classes. The first (BaseFacebook) maintains the core of the upgrade, and the second one (Facebook) is a subclass that uses PHP sessions to store the user id and access token.
Facebook has made it clear that, all website and canvas apps must exclusively support OAuth 2.0 (draft 20) by October 1, 2011. The OAuth 2.0 authorization protocol enables a third-party application to obtain limited access to an HTTP service, either on behalf of a resource owner by orchestrating an approval interaction between the resource owner and the HTTP service, or by allowing the third-party application to obtain access on its own behalf. Facebook insists all canvas apps to use the ’signed_request’ parameter. Because of this, it is mandatory for all developers to migrate to new version (v3.x.x) as older versions will stop working from October 1, 2011.


Registering your application
Steps 1 to 3 will explain the procedure of registering the application at Facebook. You need to register at Facebook and obtain App ID and App Secret, for the application to work.
Step 1:
The primary step is to visit http://developers.facebook.com/apps.
If you are visiting this URL for the first time, you will have a window similar to the one shown below in which Facebook developer app will request your permission to access your basic information.
Click the ‘Allow’ button.
Step 2:
Now you be on a page that shows you your recently viewed app. Don’t worry if it doesn’t show any app. It just means that you haven’t created any app yet.
Now, click ‘Create New App’ button.
In the window that pops up, enter the name of your application. Mark the check box ‘I agree to Facebook Terms’ and click ‘Continue’ button.
Now you may be asked to solve a captcha which verifies that you are human.
Step 3:
You will be taken to the application basic settings page.
On the top portion of the page you will have your ‘App ID’ and ‘App Secret’. Please note them as we will need them in Step 5.
Enter your domain name as ‘App Domain’. Please note that a ‘your-domain.com’ will include ‘*.your-domain.com’ also. That is, you can use the app on any of your sub-domains. You can even enter ‘localhost’ if you are testing your application on your local machine.
In the ‘Website’ section, you need to enter ‘Site URL’. ‘Site URL’ will be entry page for your application. As we are making a webpage that has f-connect enabled, we need to give the address of the webpage that we are about to make. In my case, it is http://25labs.com/demo/fb/index.php. Site URL will be the redirect URL for your application. Because of security reasons, Facebook will redirect users to this URL only. We will be creating webpage in the later sections. If you are not sure about what your URL will be, just leave the field blank as you can fill it any time later.
The registration of your application is now complete. Now we will move on to build our application.
Downloading PHP SDK
Facebook releases its PHP Software Development kit so that developers can easily integrate their Graph API to the applications.
Step 4:
Download the latest version of PHP SDK from GitHub.
Extract the compressed file and you will find folders and files similar to the one shown below.
Upload the above shown folders to the webhost where you wish to have your webpage. In my case it is ‘25labs.com/demo/fb/’. For the application to run, only the folder ‘src’ is required. All other files and folders are examples, tests, logs etc and so they can be optionally discarded.
Creating the access file (fbaccess.php)
Create a file ’fbaccess.php’.
In steps 5 to 10, I will explain the file part by part.
Step 5:
The first part is Application Configurations. In this part we have 3 variables – $app_id, $app_secret, and $base_url.
Replace ‘Your App ID/API Key goes here’ and ‘Your App secret goes here’ with the ‘App ID’ and ‘App Secret’ that you created in Step 3, respectively.
Replace ‘Your Site URL goes here’ with the ‘Site URL’ that you entered in Step 3. If you are still not sure of your site URL, leave it as such. You can come back and edit it after step 11.
$app_id = "Your App ID/API Key goes here"; $app_secret = "Your App secret goes here"; $site_url = "Your Site URL goes here"; |
Step 6:
Now, include ‘facebook.php’ which can be found in the ‘src’ folder of PHP SD that you downloaded.
Then you need to create an application instance using the constructor of class ‘Facebook’. The App ID and App Secret need to be passed as arguments for the constructor. In earlier versions of PHP SDK (v2.x.x), the argument array had an optional key ‘session’. But in v3.x.x, ‘session’ key is not used at all.
Then we call the function getUser() which will return the user ID. We will be using a variable ‘$user’ to store the User ID of Facebook user. We may or may not have this data based on whether the user is logged in. If we have a $user id here, it means we know the user is logged into Facebook, but we don’t know if the access token is valid. An access token is invalid if the user logged out of Facebook.
include_once "src/facebook.php"; $facebook = new Facebook(array( 'appId' => $app_id, 'secret' => $app_secret, )); $user = $facebook->getUser(); |
Step 7:
If we get a User ID in the previous step, it means that we have a logged in user. Now we need to check whether the logged in user is authenticated to run the application.
For this, we call the ‘api’ function with value ‘/me’. If the user is authenticated, api(‘/me’) will return the profile information of the user. If the user is not authenticated, the function will produce an exception. We catch this exception and then make the ‘$user’ variable NULL so that the user can be asked to authenticate.
if($user){ //==================== Single query method ====================================== try{ // Proceed knowing you have a logged in user who's authenticated. $user_profile = $facebook->api('/me'); }catch(FacebookApiException $e){ error_log($e); $user = NULL; } //==================== Single query method ends ================================= } |
This try catch-block is also an example for single query method. Different arguments can be used for function ‘api’ to return various results for authenticated users in single query method. Full set of arguments can be found at https://developers.facebook.com/docs/reference/api/
Step 8:
After Step 7, variable ‘$user’ will hold Facebook User ID if we have a logged in authenticated user, and NULL otherwise.
If it holds a User ID, it means that the user is logged into the application. So we need a logout URL. If the variable is NULL, it means that user is not logged in and we need a login URL.
We use functions getLoginUrl() and getLogoutUrl() to get the login and logout URL respectively. The argument for getLoginUrl() is an array with optional keys ‘scope’ and ‘redirect_uri’.
$loginUrl = $facebook->getLoginUrl(array( 'scope' => 'Your list of Permissions', // Permissions to request from the user 'redirect_uri' => 'Your Site URL', // URL to redirect the user to once the login/authorization process is complete. )); |
The ‘scope’ field will contain a comma separated list of permissions to request from the user. You must ask for all the permissions that you need for the app to work. For example, if you need email, birthday and location of the user, then you must specify ‘email, user_birthday,user_location’ in the scope field. In my case, I need permission to retrieve news feed, publish stream, birthday, location, work history, hometown and user photos. Thus my ‘scope’ parameter is ‘read_stream, publish_stream, user_birthday, user_location, user_work_history, user_hometown, user_photos’. You can read about the full list of permissions at https://developers.facebook.com/docs/reference/api/permissions/.
‘redirect_uri’ field will contain the URL to redirect the user to, once the login/authorization process is complete. The user will be redirected to the URL on both login success and failure. If this property is not specified, the user will be redirected to the current URL (i.e. the URL of the page where this method was called, typically the current URL in the user’s browser).
The argument for getLogoutUrl() is an optional array with key ‘next’ which contain Next URL to which to redirect the user after logging out.
$logoutUrl = $facebook->getLogoutUrl(array( 'next' => 'Your Redirect URL after logout', // URL to which to redirect the user after logging out )); |
Please note that it should be an absolute URL. If this property is not specified, the user will be redirected to the current URL.
For my application webpage, the complete code for login and logout URL is shown below.
if($user){ // Get logout URL $logoutUrl = $facebook->getLogoutUrl(); }else{ // Get login URL $loginUrl = $facebook->getLoginUrl(array( 'scope' => 'read_stream, publish_stream, user_birthday, user_location, user_work_history, user_hometown, user_photos', )); } |
Step 9:
Now we need to retrieve the information that we need if we have a logged in authenticated user. For that we can use the single query method mentioned in Step 7. The below code retrieve user info, news feed, friends list and photos of the logged in user. You can also specify an optional limit for many queries.
try{ $user_info = $facebook->api('/' . $user); $feed = $facebook->api('/' . $user . '/home?limit=50'); $friends_list = $facebook->api('/' . $user . '/friends'); $photos = $facebook->api('/' . $user . '/photos?limit=6'); }catch(FacebookApiException $e){ error_log($e); } |
You can notice that it takes 4 requests to the graph API. It can slow down the page significantly and also increase the load. So it will be better if we can combine all these requests. For that we use Batch requests. All the queries can be saved to an array. We encode the array as JSON and POST this JSON to batch endpoint on the graph. It will return values that are indexed in order of the original array. The content will be in ['body'] as a JSON and we need to decode the JSON to get the results as a PHP array. Batch query replacement for single query method is shown below.
//========= Batch requests over the Facebook Graph API using the PHP-SDK ======== // Save your method calls into an array $queries = array( array('method' => 'GET', 'relative_url' => '/'.$user), array('method' => 'GET', 'relative_url' => '/'.$user.'/home?limit=50'), array('method' => 'GET', 'relative_url' => '/'.$user.'/friends'), array('method' => 'GET', 'relative_url' => '/'.$user.'/photos?limit=6'), ); // POST your queries to the batch endpoint on the graph. try{ $batchResponse = $facebook->api('?batch='.json_encode($queries), 'POST'); }catch(Exception $o){ error_log($o); } //Return values are indexed in order of the original array, content is in ['body'] as a JSON //string. Decode for use as a PHP array. $user_info = json_decode($batchResponse[0]['body'], TRUE); $feed = json_decode($batchResponse[1]['body'], TRUE); $friends_list = json_decode($batchResponse[2]['body'], TRUE); $photos = json_decode($batchResponse[3]['body'], TRUE); //========= Batch requests over the Facebook Graph API using the PHP-SDK ends ===== |
Step 10:
You can update user’s status by using the method mentioned below. We POST the status to ‘/UserID/feed’. (‘UserID’ to be replaced with the required user’s ID). The status to be posted is an array with optional fields – message, link, picture, name, caption, and description.
try { $publishStream = $facebook->api("/$user/feed", 'post', array( 'message' => 'Check out 25 labs', 'link' => 'http://25labs.com', 'picture' => 'http://25labs.com/images/25-labs-160-160.jpg', 'name' => '25 labs', 'caption' => '25labs.com', 'description' => 'A Technology Laboratory. Highly Recomented technology blog.', )); }catch(FacebookApiException $e){ error_log($e); } |
If you just want a status message, then just omit all other fields.
try{ $statusUpdate = $facebook->api("/$user/feed", 'post', array('message'=> 'Your Status goes here')); }catch(FacebookApiException $e){ error_log($e); } |
Complete fbaccess.php for my webpage
(Codes in Step 5 to 10 combined)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 | <?php //Application Configurations $app_id = "Your App ID/API Key goes here"; $app_secret = "Your App secret goes here"; $site_url = "Your Site URL goes here"; try{ include_once "src/facebook.php"; }catch(Exception $e){ error_log($e); } // Create our application instance $facebook = new Facebook(array( 'appId' => $app_id, 'secret' => $app_secret, )); // Get User ID $user = $facebook->getUser(); // We may or may not have this data based // on whether the user is logged in. // If we have a $user id here, it means we know // the user is logged into // Facebook, but we don’t know if the access token is valid. An access // token is invalid if the user logged out of Facebook. if($user){ //==================== Single query method ====================================== try{ // Proceed knowing you have a logged in user who's authenticated. $user_profile = $facebook->api('/me'); }catch(FacebookApiException $e){ error_log($e); $user = NULL; } //==================== Single query method ends ================================= } if($user){ // Get logout URL $logoutUrl = $facebook->getLogoutUrl(); }else{ // Get login URL $loginUrl = $facebook->getLoginUrl(array( 'scope' => 'read_stream, publish_stream, user_birthday, user_location, user_work_history, user_hometown, user_photos', 'redirect_uri' => $site_url, )); } if($user){ // Proceed knowing you have a logged in user who has a valid session. //========= Batch requests over the Facebook Graph API using the PHP-SDK ======== // Save your method calls into an array $queries = array( array('method' => 'GET', 'relative_url' => '/'.$user), array('method' => 'GET', 'relative_url' => '/'.$user.'/home?limit=50'), array('method' => 'GET', 'relative_url' => '/'.$user.'/friends'), array('method' => 'GET', 'relative_url' => '/'.$user.'/photos?limit=6'), ); // POST your queries to the batch endpoint on the graph. try{ $batchResponse = $facebook->api('?batch='.json_encode($queries), 'POST'); }catch(Exception $o){ error_log($o); } //Return values are indexed in order of the original array, content is in ['body'] as a JSON //string. Decode for use as a PHP array. $user_info = json_decode($batchResponse[0]['body'], TRUE); $feed = json_decode($batchResponse[1]['body'], TRUE); $friends_list = json_decode($batchResponse[2]['body'], TRUE); $photos = json_decode($batchResponse[3]['body'], TRUE); //========= Batch requests over the Facebook Graph API using the PHP-SDK ends ===== // Update user's status using graph api if(isset($_POST['publish'])){ try{ $publishStream = $facebook->api("/$user/feed", 'post', array( 'message' => 'Check out 25 labs', 'link' => 'http://25labs.com', 'picture' => 'http://25labs.com/images/25-labs-160-160.jpg', 'name' => '25 labs', 'caption' => '25labs.com', 'description' => 'A Technology Laboratory. Highly Recomented technology blog.', )); }catch(FacebookApiException $e){ error_log($e); } } // Update user's status using graph api if(isset($_POST['status'])){ try{ $statusUpdate = $facebook->api("/$user/feed", 'post', array('message'=> $_POST['status'])); }catch(FacebookApiException $e){ error_log($e); } } } ?> |
Creating the main webpage
Now we will be creating the main page of the website. It will be the one that is visible to the users.
Step 11:
Create a PHP file (In my case it is index.php).
Include ‘fbaccess.php’ into it.
‘fbaccess.php’ will give you a NULL ‘$user’ variable and ‘$loginUrl’ for a user who is not logged in and authenticated. So, if ‘$user’ is not set, make a login button or link and make ‘$loginUrl’ its destination. User can click this button and login to your webpage.
If ‘$user’ is set (logged in authenticated user), ‘fbaccess.php’ will give you 5 variables – $logoutUrl, $user_info, $feed, $friends_list, and $photos. Except $logoutUrl, all others are PHP arrays.
If you print the array ‘$user_info’ it will look something similar to this.
Array
(
[id] => 100002936955841
[name] => Unni Krishnan
[first_name] => Unni
[last_name] => Krishnan
[link] => http://www.facebook.com/profile.php?id=100002936955841
[birthday] => 01/02/1988
[hometown] => Array
(
[id] => 110383752315912
[name] => Trivandrum, India
)
[gender] => male
[timezone] => 5.5
[locale] => en_US
[updated_time] => 2011-09-18T14:16:25+0000
) |
You can use these variables which has all the information you need, to make your webpage. Please note that user’s first name, last name and profile picture are publicly available and you don’t need PHP SDK or an access token to retrieve them.
The below mentioned link can be used to get the profile picture of a user.
https://graph.facebook.com/zuck /picture?type=large
In the above example ‘zuck’ is Mark Zuckerberg’s username.
You can specify the picture size you want with the ‘type’ argument, which should be one of square (50×50), small (50 pixels wide, variable height), normal (100 pixels wide, variable height), and large (about 200 pixels wide, variable height).
When complete, upload the page to the host where you need your f-connect enabled website need to be. Please not the URL of the page as it will act as your site URL. If you had skipped to enter the Site URL in Step 3 and 5, please go back and enter them.
You can download the complete source of my demo webpage from here.
User Authentication
When a user login at your webpage for the first time, he will have to grant permission for accessing his details. It will look similar to this.
Once the user clicks ‘Allow’ he will be redirected to your webpage as an authenticated user.
Issues you may face
Any errors that you get will be logged in your hosts error log. Please check log to get information on errors, if any.
Session Error:
You may get a similar warning in your error log.
Warning: session_start() [<a href='function.session-start'>function.session-start</a>]: Cannot send session cookie - headers already sent |
In this case getUser() function will return 0 for all users even if they are logged in. This happens because session doesn’t get saved in your host.
Solution:
Make sure the session.save_path in php.ini is set and point to a valid path. In many hosts the line session.save_path would be commented out. In that case please uncomment the line.
Hope everything worked well. Comment below if you face any problems or find any improvements to the script.



















No wrok
No wrok in localhost
I have tried it on localhost and it worked perfectly. Can you please explain in detail? What is the error that you get? Please check your error log for details.. I will try and help you..
giving error in fb.access file at ,line no. 13 that it could find class Facebook and i m trying to run on your example on localhost.com
The problem may be caused mainly because of 2 reasons.
Try:
First:
Make sure the ‘session.save_path’ in ‘php.ini’ is set and point to a valid path. In many hosts the line session.save_path would be commented out. In that case please uncomment the line.
Second:
Make sure that ‘php_curl.dll’ module is loaded.
Open ‘php.ini’ and replace:
with
That is, just un-comment (remove semi-colon) the line.
Hi. I have check the two step . But it still shows that Fatal error: Class ‘Facebook’ not found in E:\wamp\www\facebook-connect\fbconnect.php.
Could you help ? Thanks
please can you give example permisions
+++++++++++++++++
https://developers.facebook.com/docs/authentication/permissions/
+++++++++++++++++++
how to put the permission ?
Great Work. Thanks for the tutorial.
Works like a charms! Thanks a lot for this great tutorial.
The only problem that I have right now is, that he doesn’t post the link. He doesn’t show any errors. Any fox for that?
regards
Brian
Are you talking about the status update?
I haven’t set the ‘index.php’ to display errors if any. Please check your PHP error log for details. Please let me know what’s there in your error log.
No errors in the error_log. I checked the $_POST var and it’s empty. But I made it work now. (like I think you thought it should work) ;D
Thanks a lot again, and thanks for answering in the comments. Not a lot of ppl do that
Happy to hear you
I would like to thank you for this, my personal PHP skill set is to “hack” a script to learn how they work.. No one really wanted to give a COMPLETE example of anything, and your script actually works, where I couldn’t find a working example ANYWHERE!
My only question, is there some way to be able to display comments on a news feed item? I’m actually only using your script to make a script I’m writing automatically post the blog post directly to facebook (as opposed to storing it in my own database (which they’re stored in now).. basically I got this “brilliant” idea to let FB store my posts, and save myself from making user registration public..
So, long story short, is there a way to tweak your already awesome script, and let comments on news feed items show? You can e-mail me directly if you like, otherwise I’ll check here for the next few days. Thanks!
To retrieving the comments of a news feed item you can use the syntax
where OBJECT_ID is the the Post ID of the news feed item.
To integrate it to the demo code, just add the following lines after the function call newsitem() in index.php
This method works fine if you wish to retrieve the comments of 1 or 2 posts. Please note that it is always better to keep the number of API calls as low as possible. So, it is not a good idea to make this API call for each and every news feed item. Instead make a batch request over the Facebook Graph API after collecting the Post IDs of all news items for which you wish to retrieve the comments. Please let me know if you have any queries.
I have realized a major flaw in my plan.. I have successfully been able to create a FB login page, that will show you YOUR PERSONAL news feed, and separate from this, a page that pulls the news feed from a specific page (a small business I’m working with).
My problem, is I don’t know how to do these two things at the same time. At least not in the way that’s working. I was able to successfully show the feed from the business’ page, while being logged in as myself, however, it appears to be pulling random status updates from random pages, that have no connection to this business.
Is what I’m attempting to accomplish too difficult? What my final goal is desired to be:
Admin logs into the site, makes a blog post directly to FB from the admin control (also used for other things), which then is immediately posted to the main page of the site because the index.php page displays the wall posts of the business only. Then, users are able to login to their personal FB page and leave comments and/or like the article, which is also immediately displayed on index.php
Your script seems to have accomplished 80% of what I need, but I’m afraid my skills are not advanced enough to simply add the rest to your script. Any help you give would be greatly appreciated, we could even discuss some sort of compensation if this requires serious time.
What you look for is quite simple. I will email you the modified code.
sir, please tell me or send me the code of facebook api…
how can i login with facebook on my website
how i should i insert the data into database..pls help me..
Database must have a table that has fields:
‘id’ – an auto incremented value
‘user_id’ – facebook user id ($user['id'])
‘name’ – Name of user ($user['name'])
You are free to have more fields like email, date_of_birth etc etc.
When a user logs in, you must check whether the ‘user_id’ of that particular user already exists in the database and if not, you must add a new row that contains the details of the user.
You can also set cookies to identify a user.
If you wish to have access to the user details without the user logging into the system each time, you can request for ‘offline_access’ permission which give you a lifetime access token. With this access token you can get the user details even when the user is logged out of Facebook.
In few days time, I will try to post a detailed tutorial on having a complete database based Facebook connect. I need to have a thorough look at the Facebook Documentation for it.
Hi,
Just tried your scripts and it works ! thanks for that.
Just one question how do i remove the permission request as i dont need them.
Post to Facebook as you
Access posts in your News Feed
Thanks,
Ronald
The permission can be added or removed by editing the ‘scope’ in loginUrl.
For example, if you need just the basic information about the user and his email then just add ‘email’ in the scope field.
Hi I’m trying to do something similar but sending via a batch to updated multiple walls with the same message. I’m using ?batch=’.json_encode($queries) where queries is an array of users to post to.
It posts but I cant add messages or pictures etc. Any suggestions?
Even though I haven’t tried it out, I feel the method should work. Can you please let me know, the part of your script that you use to post to wall of multiple users?
Hi this is the code that I use to post to multiple walls.
I’ve left in the line
which creates the posts with the content etc but takes a long time to complete due to the multiple calls it produces.
for each friends do:
and then:
Please try the above code.
If you still don’t get it right, I will test it myself and try to help you.
hey man why when i try to post in arabic it gives me batch post faild and when i post in english letters everything works just fine ??
Try:
Hey man where to put this i dont understand where
and do you understand what i mean exactly
when i type any word in arabic in any field of those fields
it gives me falier messages
i dont understand why not arabic is not working
i tried to change it to utf-8 but nothing solved
Hi,
Thanks for the code. Unfortunatly $batchResponse now returns null and wont send any posts.
Sorry for the late response. Please check the code below. I have tried it myself and it works..
Hi Tebe,
Your a genius!
works perfectly
Thanks very much I was running out of hair to tear out!
D
Hello.
I put this into my code and $batchResponse has:
[body] => {“error”:{“message”:”(#200) The user hasn’t authorized the application to perform this action”,”type”:”OAuthException”,”code”:200}}
Can you please help?
Regards, Marek.
Maybe it’s becouse I login using phpSDK?
Great work ! It works perfectly !
Hi. First I want to thank you Soooooooooooo much for this tutorial!!!! This has been the only place when someone actually took the time to explain everything.
I have a problem with logging out. When I press the logout button it doesn’t log out of the wall and will still let me post to facebook. But if I try clicking on the fb-like box it tells me I’m logged out. Am I overlooking something? Thanks
The logging out problem occurs because you have added ‘offline_access’ to your scope parameters. If you ask for ‘offline access’ permission you will not be able to log-out of the application by clicking the logout url, but will log you out of Facebook.
And what is the solution in this case, because we have to show the user a logout button/link.
We have to create a dedicated one ? If yes, the user will puss the button/link and will be redirected to the controller which holds the logout method (in case of a framework – FuelPHP).
How will kill the controller the $facebook SESSION ? Because I think that first we have to kill the Session and then to redirect him to the login page ! Correct?
P.S. Great tutorial, for beginners (as I am).
What about the access token and its expiry time?
By default the access token have a 2 hour lifetime. But if you add ‘offline_access’ to the scope, then the access token returned will be long-lived.
Also how do you enable the user to “comment” on each feed item displayed?
Each feed item will have an id (in our script its $news['id']).
Replace “1000xxxx2925682_1774xxxx9027393″ with the id of the feed item. You will have ‘Hi, how r u??’ as the comment.
Where would this go? Sorry I’m a newb.
In index.php, add the above lines of code immediately after the below line:
Also add the following lines to fbaccess.php just before the closing bracket.
Thanks. That worked perfectly!
I’m including ‘display’ => ‘popup’ in the parameters of loginUrl , but still im not getting a popup window! I’m getting a whole page! I really wanna know the solution for this
Just by including ‘display’ => ‘popup’ in the login parameters you will not get a popup window. Instead, you will need to use a javascript popup window using window.open() function.
Thank you
Works like a charm,thanks a lot thats the best example i’ve found.I had some problems with the ‘logout’ but then i noticed i didnt add the ‘next’ clause into the fbaccess file
HI. I using 1998-2008 Zend Studio and WampServer Version 2.1 I downloaded the php sdk, but when I includ-ing the facebook.php file , everithing its after this include is not displayed. Somebody know what is the problem? I speak only a little English, but I hope that you understand the problem.
may the problem that I using this in localhost?
The script will work fine even if it is run in localhost.
Please try to include facebook.php file before sending any headers to the browser. Make
the first statement in the file. I hope it will solve the issue.
I find the proble.
when I changed from thist ;extension=php_curl.dll
to this extension=php_curl.dll in wampserver php.ini file,its work fine.
Happy to hear you..
Finaly finished the facebook login and logout.
And it’s working fine.
Best tutorial so far, works great, Thx!
When you call the queries right at this point:
then you decode them:
do you have a list of options i can use?like i want to get the “notes” or “about me” page for the user,but i get an error 2500
i know i need the user_about_me permission in the scope and i already have it,i just cant receive anything
To retrieve “about me”, you need to ask for ‘user_about_me’ permission and then:
You will have the “about me” in $user_info['bio'].
To retrieve “notes”, you need ‘user_notes’ permission and then:
yes thanks,after a while i figured i already had the infos i wanted under ‘bio’. as for the options,i found a nice app for the graph api here: https://developers.facebook.com/tools/explorer so i can check there each time i need a specific option
Hi i have problem i got message
Fatal error: Class ‘Facebook’ not found in C:\wamp\www\Proba\fbaccess.php on line 17
and dont wont work please help.
It happens because you haven’t copied the files ‘facebook.php’ and ‘base_facebook.php’.
iam also getting the same error ..i have copied src folder to current directory..
Make sure that ‘php_curl.dll’ module is loaded.
Open ‘php.ini’ and replace:
with
That is, just un-comment (remove semi-colon) the line.
Hi Tebe, thank you so much for this tutorial first of all.
Unfortunately, I wasn’t able to get it to work because getUser() function keeps giving me 0. Are you familiar with CodeIgniter by any chance? This might be a silly question, but would it be a problem with my application using CI Session?
I am sorry that am not familiar with codeigniter.
Please make sure that your session gets saved. getUser() function will always returns 0 if the session doesn’t get saved.
Have the same issue that “$facebook->getUser()” returns 0 … what you mean exactly that “make sure your session gets saved”?
The problem is caused mainly because of 2 reasons. Try:
First:
Make sure the ‘session.save_path’ in ‘php.ini’ is set and point to a valid path. In many hosts the line ‘session.save_path’ would be commented out. In that case please uncomment the line.
Second:
Make sure that ‘php_curl.dll’ module is loaded.
Open ‘php.ini’ and replace:
with
That is, just un-comment (remove semi-colon) the line.
good
Hi tebe, thanks for the tutorial.
I have a problem, after logging in, why user still not log in? it still display fb connect button, not redirect into user profile.
the url display : http://localhost/fbdemo/?state=332471d23af6f93fbcb511c75881c6c6&code=AQBIVrLZ8OI9w_48-6WEVuIoqhMwLuiP1G1dXvr78jO6YvhIe6a0-s2aklyMx6oCTVlGV9Ki6RPIP2Gjwd3ZydPSK3gDSMrgsWyBswSQW1j7RezNJauYTqYcPUApSDu8b6RAgU-1KW183RYD1fIB7PJIU0DHMVFkvkoabmSP0kKlIP_r0JJfExyy-p5Pyr7Sj5Y#_=_
Please help me. sorry, bad english.
I am having the same problem, did you find any solution?
$user always return zero, I also uncommented the line session.save_path in php.ini but it still doesn’t work
the path is set to N;path/
Is this a valid path?
From your comment I feel that you uncommented the line:
Actually, that is not the line to uncomment.
When you are using localhost, the line to uncomment in ‘php.ini’ will be similar to:
“N;/path” is not a valid path. Its just instruction on how to set the path.
valid path will be similar to “\xampp\tmp”
hi, I followed your instruction you gave about save_path, I changed save_path using:
session_save_path(“/home/myusername/tmp”);
even now it creates temp files at that directory with names like:
“sess_b6e48b55336c14f277ba4cb540dc4fa2″ – but $facebook->getUser() still returns 0 (zero,null).
Have you any idea?
I am not sure of any other solution. Please comment if you have somehow solved the problem.
did anyone solve this? i’m having the same problem, after i accept everything with facebook and returne to index.php it doesn’t show me anything but the same page, as if $user still logged out. If i try “login” again does recognize me and doesnt’t ask again for authorization but i’m still in the unlogged index.php
Pleas help.
i’m a newbie, i’ve already created the fbaccess.php file and included into my index.php, but the problem is that i don’t know how to make a “facebook login button” in my index.php, so that way it could initiated the whole process with fbaccess.php file.
i’ve been trying to make it like this(index.php):
help me pls
where $loginUrl is the variable that contains the login URL.
very good tutorial
news feed don’t work with new PHP SDK
error line 164
I have tried it with latest PHP SDK and couldn’t find any errors. I have updated the demo with new PHP SDK and it works fine with out any change in code.
Let me explain it. I’ve got 3 files : fbaccess.php, facebook.php and index.php
i’ve already include facebook.php into fbaccess.php, then if i’m gonna include fbaccess.php into index.php, my big question is:
HOW DO I TRIGGER THE LOGIN BUTTON AND THE SCRIPT from my index.php? what should i have in my index.php?? i don´t know! my index.php is empty.
also: how do you use this step 2: http://developers.facebook.com/docs/opengraph/tutorial/#sample the JAVASCRIPT SDK, should i paste it in my index.php???
THANKS!
A simple ‘index.php’ will be similar to:
The above script will print your user_info, feed, friends_list and photos if the user is logged in. And it will display the login link if the user is logged out.
Thanks … so great to finally got it!
-But now how do i DISPLAY THE LOGIN OUT LINK when the user is logged in?
-And Finally could you please show you source code for connecting with MySQL? (dbconfig.php or other file u used to use)
thanks you made my day.
You can display the logout link with code similar to:
Actually for this kind of stuff I don’t use a database. When ever the user logs in to this application we can retrieve all the details from Facebook. So there is no point in storing all the data at your server.
But if you wish to make a database of users, then just create a table with all the fields that you require and insert the required data when the user logs in.
Create a database:
Insert into database:
I’m still no get it the “LOGOUT LINK”. It doesn’t displaying it at all.
check this out: http://prueba001.net78.net/probando/
I’ve been trying but not even display any “echo” statements after “else”.
What am i doing wrong?
You have given the Site URL as http://prueba001.net78.net/
In your case it should be http://prueba001.net78.net/probando/
it works! thanks a lot!
“When ever the user logs in to this application we can retrieve all the details from Facebook. So there is no point in storing all the data at your server.”
How would you initiate a call for this info again?
Hello,
I have a problem with the logout, each time i visit index.php is like i’m logged in but i’m not, it should redirect me to the connect again.
Do you think you can mail me clean version (without all the other graphics) just with username and photo and login logout?
email: evilmini_me_2002@yahoo.com
Thnx.
The logout problem is because of a recent Facebook API change – ‘offline_access Permission Removal’.
Because of the change, by default, an access_token is valid for 60 days. So even if you log out of Facebook your app will remain logged in as the access token doesn’t get expired.
You can use the old API till May 01, 2012 by disabling the ‘Deprecate offline access’ setting from Edit App > Advanced > Migrations tab. Its currently enabled by default for any newly created apps. Disabling it will solve your issue for time being. This is the simplest solution to your problem.
You can read more about it at:
http://developers.facebook.com/roadmap/offline-access-removal/
And now, simple ‘index.php’ with just login or logout link, username and photo will be:
Thnx Tebe
It seems when i do this, i get this error…
Warning: session_start() [function.session-start]: Cannot send session cache limiter – headers already sent (output started at /home/******/public_html/***********/fbnew/index2.php:2) in /home/******/public_html/***********/fbnew/src/facebook.php on line 37, also, when you press logout, it still doesnt go back to original log in.
Hi! great tutorial! i was wondering if you could help me doing a SESSION with PHP, MySQL and facebook connect.
i’ve already created my database but i don’t know how does it works together with PHP SESSIONS and facebook connect.
i’m trying to do it like this.
but i’m still not get it the index.php file from the other tutorial. and nobody answers my questions.
could you please help me?
Why you wish to use SESSION? Actually do you wish to remember a user in your browser? If yes, there is no point using a SESSION as it will be cleared when you close the browser.
I may be able to help you if you can clearly inform me what are your requirements. Why do you use a database? Do you wish to remember a user once he logged into your webpage? etc etc..
here is what i wanna do:
i want to create a facebook connect based membership system for my web app, i don’t want to use forms for main information about a user.
I gonna use forms AFTER they sign up/register using Facebook Connect.(these forms contains extra but important info that is gonna run my whole web app and their dynamic between users)
Then the users are gonna be redirected to their profile.(just already build/done using forms)
Finally users profiles are gonna have the following:
-pictures (upload system)
-basic info and extra
-thumbnail with the facebook profile picture(small,resize) of the user
-and something (i wanna your adviced) that could use to flow comuncation between users. like implementing a facebook comment system.
ps: my project is like a online dating site.
ps2: i’m a newbie about building membership systems and i’ve been watching videos on youtube and the authors are telling people that this kind of system is using php session.
A SESSION is REQUEST variable that is used normally to store or remember something in a browser till the user closes the browser. In your case you need not use a SESSION as all those work will be done by Facebook Connect. Remembering your user (till you close the browser), managing the login/logout etc is Facebook Connect’s job and you need not worry about it.
Keeping everything simple, you can do it with minimum script. A small script to help you is shown below. Please make a note that below script don’t use a custom COOKIE or save the access_token. So there won’t be a ‘Remember Me’ option.
Create a database:
‘index.php’ with insertion of user data and detail retrieval:
In the ‘have a registered logged in user’ section you can use a form to collect the new data and associate it with the logged in user.
After the For the comment system just create your own system which suits your needs. Create a table for it with necessary details.
Thanks! your script rockz! this is the last one, where exactly do i have to put this file? like an “include” into index.php with a different name ( include dbconfig.php)? or at the beginning of index.php before doctype?
only at index.php?
Actually the above script is index.php + dbconfig.php combined. So name it ‘index.php’. All the code that is necessary for database management is included in it. Please include your requirements like styling, doctype etc into and you are done.
Hi tebe, I checked and test a long time, finally I found the reason why getUser() function always returns 0
Please login developer apps, in settings–>Advance–>Migrations–>Deprecate offline access–>disabled.
we will find $facebook->getUser() will work.
Hope this help. Thanks for the tutorial
Happy to hear that your problem is solved.
But I am still confused how that setting caused the error. I have tried the script with ‘Depreciate offline access’ enabled as well as disabled. In both cases the script worked fine. Only problem of the setting was that, if you keep it enabled, you will not be able to log out of the app by clicking the logout link. This happens because the access token returned with Depreciate offline access enabled will be long lived (60 days).
I didn’t find any option in migration-> deprecate offline access-> disabled
Hello I am trying to setup ur timeline posting app but it seems not working
Here is my link
http://fb.greenbd.net/timelinepost
Where is my problem ?? Can you suggest me ??
Advance Thanks
I like this site … I am researching something api related finally got here !! So i specially want to give a thank to Tebe .
But i have a little problem still may be it can be solve with help of Tebe . Please suggest me .. Where i have to change ?
http://fb.greenbd.net/timelinepost
Not working properly ..
I couldn’t identify the problem from the url. Can you please change the ‘index.php’ to:
Please run the above code and check whether the Login link change to Logout and viceversa on login/logout. Please let me know the result and I will try to help you.
Thanks Tebe for instant reply .. I changed it !!
It shows login I mean $user variable not getting … But why ?/
Lets see :
http://fb.greenbd.net/timelinepost
Please check your ‘php.ini’ and see whether ‘session.save_path’ is set and is point to a valid path. In many hosts the line session.save_path would be commented out. Please make sure that you set it to valid path if not set.
Thanks Tebe , But I have already running an application like facebook user access ..
You can take a look here :
http://fb.greenbd.net/fbk
So dont think that php.ini is issue .
Please help me !
You have given your Site URL as http://fb.greenbd.net/timelinepost
Please change it to http://fb.greenbd.net/timelinepost/
Please note the trailing slash(/). I suppose it will solve your issue.
Thank you very Much … You are really genius ..
Problem solved !
very helpful site !!
Hi Tebe, i wanna know how do i have to name my site URL in my facebook app, if i wanna work on localhost??
http://localhost:projectname/ ?
or
http://localhost/projectname/index.html ?
Also on fbacces.php how do i have to name $siteURL ? remember localhost
You may specify the SiteURL as
http://localhost/projectname/
or
http://localhost/projectname/index.php
Use the same in ‘fbaccess.php’ also.
Hi excellent tutorial!
I’ve got a newbie problem!
let me explain it:
I’m trying to use a lightbox (jquery popup box) everytime the user clicks on Login or Sign Up (header links)
But when i put the php code for facebook connect. i’ve got the “else” and echo statements, a portion of the code.
check my code pls:
even if try to put some php code like a echo statement, i’ve got nothing!
i’ve got something only if i put a text into it, like this:
hello!
what am i doing wrong??
plz help me!
ps: my jquery code is fine. the problem i think is php with html code.(embed)
Never mind! the problem was the extension file (.php)
But i’ve got another problem, when the user login with facebook connect, everything fine, except when the user try to click again the link login inside a lightbox (popup box) it gets the logout link(like it supposed to do) but with a error batch response fbaccess.php on line 73 to 75.
(//Return values are indexed in order of the original array, content is in ['body'] as a JSON
//string. Decode for use as a PHP array.)
why is that?
I am not sure why it happens.
You can try disabling the ‘Deprecate offline access’ setting from Edit App > Advanced > Migrations tab. Its currently enabled by default for any newly created apps.
Facebook has recently changed this. They are taking off the offline_access Permission. And the result is a long lived access token with a validity of 60 days for all users.
i’ve got a question, how do you edit fbaccess.php if wanna redirect the user to a another url but index.php
after they finished the process of facebook connect?
I didn’t get you actually.
Do you wish to have all your users on say, ‘abc.php’ once they login?
yes exactly. like this page:
try to login with facebook connect and when you finished the process it takes you to another page (other than index.php)
Just specify ‘abc.php’ as your Site URL.
You will get redirected to ‘abc.php’ after the login authentication.
sorry to bothering you again but i’ve got this problem:
i already logout of facebook but everytime i go/clicked to the Login or Sign Up link of my app, it’s get me the facebook logout(url).
how can i change that? because i wanna try again to login and test my app many times.
ps: i’m working on localhost.
Disable the ‘Deprecate offline access’ setting from Edit App > Advanced > Migrations tab
i have disabled “deprecate offline access” but it keeps telling me that i’m logged in when i actually already logged out.
what’s happening?
ps: i’m working on localhost.
I cannot say much without seeing the code or atleast try your webpage myself. It can be some refresh issues as you use lightbox.
Once again i am here !! By this process i can post and multi time line post . But i now just tried to tag one of my album photo with my friend list.
I can now load all albums and and photos but how to tag with my friend no idea …. research more ..
Finally thinking about Tebe ..:)
Please can you help me ??
You can tag your friends using the above script. Make sure you ask for ‘publish_stream’ and ‘user_photos’ permissions. Also note that x and y is in percentage.
Ok thanks Let me try it !!
For adding Tagging Text I am doing :
Is it correct ??
You must specify either the ‘to’ or ‘tag_text’ parameter, but not both.
Parse error: syntax error, unexpected $end in C:\wamp\www\proyecto001\index.php on line 264
on line 264 i only have a
my index.php is like this:
some code
</html
why is that?
help me plzzz!
Do you use any Short Open tags ( ‘< ?' for opening a php script )?
In that case please use
instead of
for opening a php script in all your code.
If you wish to use Short Open tags, you need to enable it in 'php.ini'
actually i’m not using short tags. what i’m trying to do is put some php code at the header of my page then in the middle html code and finally i close my html tag. and that is the line 264 where is my /html close tag.
my file is .php extension.
what am i doing wrong?
Also could you pls show me how do you use doctype! in .php files?
ps:like i said before i’m just beginning coding in php this last week.
This is how to code in php+html. You can open and close php tags where ever you like.
thanks!
First let me say this is an OUTSTANDING tutorial.
Now my problem. As a volunteer, I have created a fundraising web site for a non-profit organization where folks compete against each other to raise funds for the organization. Each person who signs up gets their own web page to show their fundraising progress. I want to show on each user’s fundraising page stuff from their Facebook profile.
I test it with an instance of IE, the users creates their account and their fundraising page is created with their Facebook info showing. I then launch an instance of FireFox and access their fundraising page, but get no Facebook information. The web page throws an exception:
[message] => Invalid OAuth access token.
[type] => OAuthException
[code] => 190
so I have an access token problem (I save it in a database after the user authenticates and allows the app to have permission to access the user's Facebook stuff). I am not using offline_access as it is deprecated. I have enabled the migration of that which I think means that when I get my token it should be live for 60 days, but no joy.
Is what I am trying to do possible? I have read the https://developers.facebook.com/docs/offline-access-deprecation/
document concerning server side authorization, but I can't get it to work.
I must be missing something so any advice of where to look or how to proceed would be a great help.
Thanks again for a great post!
When ever you need information about a particular user (in you case fund raising page), just get the access token for the particular user from the database and set it for the page using:
That is exactly what I have been trying to do. But my access tokens are not changing per user, I must be getting the wrong token. I must
be getting an app access token perhaps. I tried:
https://graph.facebook.com/oauth/access_token?
client_id=APP_ID&
client_secret=APP_SECRET&
grant_type=fb_exchange_token&
fb_exchange_token=EXISTING_ACCESS_TOKEN
but it doesn’t give me anything. Any suggestions? Thanks again – Jim
The above code will give you the access token.
It turns out that there was nothing wrong with my access_token, but I was using it wrong. If I do the following:
where I have added the ‘access=token=…’ to the ‘/user’, it works for the first part of the multiple query, but I get the error “Error validating application” on the second query. Please note that when I run the code above with the second part of the query ‘/photos?limit=6&access_token=…’ it fails. I also tried putting the access token on the main part of the query “…api(‘?access_toke=…&batch=’ . json_encode($qu…” and that fails. Any suggestions?
On the up side, things are working much better and I am almost there. Thanks for your help.
The following worked, but it gave me all of the pictures, I would like to limit them to 6 like in the example:
I have tried it and it works for me.
I get a:
batch parameter must be a JSON array
error when I try that. So I searched on that and found that it works if you replace the & with %26, see the following post:
http://forum.developers.facebook.net/viewtopic.php?id=94694
So now there is much joy and happiness – Thanks
I always use urlencode() function to solve that issue. I didn’t come up with that problem as I used the below code to call the batch query.
I’m trying to get the user to 2 different redirect uri, the first when they clicked on Sign Up (after faceook connect process), they will go to a form; the second when they clicked on Login (after facebook connect process), they will go to their profile.
how do you accomplished that? Oauth 2.0 can do that?
For what I have understood from Facebook API documentation, a particular app can redirect to only one specified Site URL.
But in your case you can solve the issue by specifying a third page (inter.php) as the Site URL and then redirecting from third page (inter.php) to first page(aftersignup.php) or second page (afterlogin.php) according to your need.
If a user signs up or login, he will get redirected to inter.php by Facebook and there you can check whether the user exists in database. If user exists redirect him to afterlogin.php and if not insert into database and then redirect to aftersignup.php
thanks i’m gonna try it!
I have a doubt, i wanna get my Submit bottom to do 2 things:
1. insert data to db
2. get the user to another page
do you know how to do that? some script you used to use?
Simple method is to do the database insert in the new page(the action page).
form.php :
newpage.php :
thanks a lot!
I’m having a problem inserting data into database.
I have no real data in my database, my code is inserting data like an array.
check my code plz:
Also this is my html form:
what am i doing wrong?
It looks like you might have extra spaces in there. Also, it is a good idea to escape your strings to handle names like O’Donald, etc.
Try this:
$MYSQL_Name = mysql_real_escape_string($_POST['name']);
mysql_query(“INSERT INTO cursortable (`NAME`, …) VALUES(‘$MYSQL_Name’, …)”, $conn);
and see if that helps at all.
How posible random friends show in this code
Friends ()
<?php
$i=1;
foreach($friends_list['data'] as $frnd) {
echo '‘ . $frnd['name'] . ‘‘;
if(++$i > 10) break;
}
?>
Try the above code.
it gets me “failed”. could you plz show me a code for creating the database, html form and dbconfig.php that works for you.
because i’ve been trying to do this since 5 hours ago.
something simple, but that you already test it.
never mind. i got it! the problem was in the variables.
thanks anyway.
Thanks Tebe . Really Helpful blog !
Now i want to share a photo from my album . I already populate album list and photos of albums
Now want to share this with my friends or selected friends .
Have any idea ?
Advance THANKS
Are you talking about the privacy settings or wish to post the pic or album to friend’s timeline?
Yes i m talking about post the pic which exist in my album to friend’s time line .
This is the basic array that you need to post to your friends wall..
Here [link] is the [link] field returned by Facebook API when you query for the photo.
[object_id] is the photo id
Fatal error: Class ‘Facebook’ not found in C:\xampp\htdocs\bumbleBid\fbaccess.php on line 14
This is my error. Please help me.
Have you copied the folder ‘src’ from Facebook PHP SDK and included ‘src/facebook.php’ into fbaccess.php ???
Make sure that ‘php_curl.dll’ module is loaded.
Open ‘php.ini’ and replace:
with
That is, just un-comment (remove semi-colon) the line.
Suppose i have i photo with ID 123457678 and have 300 friends . I want to tag this photo with my 300 friends . Is it possible 300 friends to tag ? If possible then how can do this by batch process with a group with 50 friends? Actually i need faster method .
Or Alternate algorithm
I have 5 photos with 5 ID’s then i want to batch process for 300 friends . Is it possible ? and what will be faster process ??
Advance Thanks
@Tebe
For each photo you need just one API call (with out batch request) to tag a maximum of 50 friends in the photo. Please note that the maximum number of tags allowed in a photo is 50. Refer: http://www.facebook.com/help/?faq=217258071632275
You can use the below script to tag upto 50 photos with any number of friends (max.50 tags) in each photo.
Thanks Tebe !!
Hello Tebe take a look
This was my previous code . Here i got 2 variables as a string . Then i explode with their ‘-’ separator . And this String submitted by AJAX call back ..
I made group for 40 friends ID s for 1 photo by looping .
It works fine and Tagging all friends but It takes long times when i select about 200 friends .
Can you suggest me with coding for getting better performance?
Thanks
Your inner ‘for’ loop has a Graph API request. It means that there will be 40*200 requests.
You can cut it down to (400*200)/50 with the code below.
Thanks ! Tebe ,
Let me try this !
Hello man
Nice script just what I wanted. successfully installed in my server . but problem is when I hit logout button it doesn’t logout . It just stay same with a page reload . Same in your demo too. Can you tell me what it the problem ?
Thanks in advance
The logout problem is because of a recent Facebook API change – ‘offline_access Permission Removal’.
Because of the change, by default, an access_token is valid for 60 days. So even if you log out of Facebook your app will remain logged in as the access token doesn’t get expired.
You can use the old API till May 01, 2012 by disabling the ‘Deprecate offline access’ setting from Edit App > Advanced > Migrations tab. Its currently enabled by default for any newly created apps. Disabling it will solve your issue for time being. This is the simplest solution to your problem.
You can read more about it at: http://developers.facebook.com/roadmap/offline-access-removal/
Great tutorial! however i don’t know how to insert the user_id in my database, i’m trying this code:
But i’m getting the welcome message again and again, and my database is EMPTY.
just in case, my code for the index.php is this:
could you please help me out?
The only error that I could find out is in the SQL insert statement. In the statement field1 and field2 are missing. But that is not the reason for the issue that you face.
By seeing only this part of the code I cannot help you much.
This is Robbert, I just read through your blog and I’m very interested of it, because I am doing a facebook canvas project. But now, I do really hope that you can do me a favour, because I think I am facing a problem which might be related to the “access token”. The situation is I have to login to my app again and again after every hour, it seems that the access token will be expired in an hour after you login (actually I really don’t know how to extend it), and I’d searched on Google.com and stackoverflow.com, but still can’t get the answer I want, so I hope that you can solve my question.
Many thanks and have a nice day.
As offline access is depreciated recently by Facebook and any newly created app has an access token which is long lived (access token valid for 60 days).
Earlier access tokens had a validity of 2 hours unless ‘offline_access’ permission was granted.
Please make sure that ‘Deprecate offline access’ is enabled for your app and then the access token will have a validity of 60 days.
You can enable the setting from Edit App > Advanced > Migrations tab.
Its currently enabled by default for any newly created apps.
You can extend the validity of access token by:
You can read more about it at http://developers.facebook.com/docs/offline-access-deprecation/
Hi Tebe,
Thanks for your kindly reply, I pretty sure that I’d enabled ‘Deprecate offline access’in my app setting, but the validity of the token is still an hour, please browse this image to see my token vadility:- http://shopalink.web44.net/fb_login/ac1.png.
Thanks for the coding you provide, may I know how can I insert this coding to my php file? sorry, I am new on this, I do really hope that someone can teach me step by step, thanks and have a great day.
This is what I get when I disabled ‘Deprecate offline access’
And when I enabled ‘Deprecate offline access’ I get:
Please note that any old access token generated will be valid till the time it expires, even if we toggle between enable/disable ‘Deprecate offline access’.
So you need to use the access token generated with ‘Deprecate offline access’ enabled to have 60 days validity.
Are you sure that you are using the access token that was generated when ‘Deprecate offline access’ was enabled?
Are you asking for the php code to extend access token validity?
Hi Tebe,
Yeah, I pretty sure that I’d enabled ‘Deprecate offline access’ before generating the access token, and I’d tried again just now but the result is still the same:-
App ID: 4047416xx886356 : Sample TutorialUser ID:523xx8991 : xxx
Issued: 1332910800 : 37 minutes left
Expires:1332914400 : about an hour left
Valid: True
Origin: Web
Scopes: create_note email photo_upload publish_stream read_friendlists share_item status_update user_about_me user_birthday user_hometown user_location user_work_history video_upload
is it my scope problems or my coding problem? should I need to insert the code you given into my php file? if yes, may I know where should I put it?
Thanks for spending your time to teach me.
Actually you need not insert the code to extend the validity.
I recommend to try figure out the problem and get the access token with validity of 60 days.
Please try creating a new app and try the application with new app id and secret. If it still doesn’t solve the problem, please let me know the code that you use to login to your app and generate the access token. You can use the contact form if you have any problem of code privacy.
Hi Tebe,
I am opening a new app and try again later, many thanks for your kindly help, do you mind to leave your IM details, I always would like to have a smart friend like you, thanks and have a nice day.
What type of Authentication do you use? Client-side authentication or Server-Side Authentication.
If you are using client side authentication, the access token returned will be of short duration even if you enable ‘Deprecate offline access’.
Facebook Documentation states:
If the access_token is generated from a server-side OAuth call, the resulting access_token will have the longer expiration time.
Hi Tebe,
I don’t know which authentication I am using, I just use your given coding as an example, I just found a mistake in my new app (I am using your coding too in this new app), the validity of access token is 2 months, but once I close the browser and re-open again, it will ask me to login again, the access token is still existing, but it seems not binding with the FB account, I don’t know why…
From what I understand, you need to display a login button if the user is not logged into Facebook or if the logged in user is first time user of your app. And if a user is logged into Facebook and a returning user of your app, then you need to take him directly to your app without asking him to login. Right?
By using only the Facebook PHP SDK (server side authentication) you cannot detect whether a user is logged in or not. And so you cannot achieve what you need just by using PHP SDK. You will need to combine client side authentication (js SDK) with PHP SDK to achieve it.
If you plan to use only PHP SDK, then you can let ALL your users to automatically redirect to your app authentication window. If the user is already authenticated to your app then he will automatically get redirected to the logged in page.
To do it, Replace the link to login with javascript redirect to login URL.
That is, replace:
with
Hi Tebe,
Thanks for your kindly reply, using PHP SDK combine withjs SDK client side authentication, do you mean the code below to the index file?
if yes, and I’d tried already, it can detect whether user is login, but the access token it generated is just validity in 2 hours, I don’t know why…do you have any idea?
Yeah.. You are right. By using JavaScript SDK you can get only short lived (2 hour validity) access token, because its Client-side Authentication.
But you can extend its validity to 2 months by the method shown below (Server-Side Authentication).
Just call this URL with your App ID, App Secret and your 2 hour access token. The URL will return the new access token with 60 days validity.
Hello again TEBE,
Few weeks again you gave me a code for simple login, can you please tell me how to add those info “email,name,id” into mysql database? i mean the query.
Thxn in advance.
Hi Tebe,
I just update the coding as below, but I don’t know whether it is correct, can you please check for me? :-
Thanks and have a nice day.
You are right. This code will extend the validity of existing access token.
Are you trying to extend short lived (2 hours) access token to long lived (2 months) access token??
Hi Tebe,
yeah, is there any problems if I extend the access token?
There is no problem if you extend the validity.
Do you pass the short lived access token to PHP SDK? How do you get the short lived access token in PHP SDK?
Hi Tebe,
I’d tried several times for the coding above, as I know it is workable, $access_token = $facebook->getAccessToken(); -> this is the code to fetch the current/new access token (if you are using JavaScript SDK, this token might be expired in 2 hours). If you insert the CURL code above, it will automatically exchange a long live token to you which is always vidility in 2 months, after this, no matter how many times you login by using this coding, the access token will not be changed, that is the result I get from the coding above, please do let me know if I get anything wrong, I would like to learn this perfectly, thanks for helping me this, Tebe.
What you are doing is right.
The access token validity will be extended just once every day. That is why you don’t see any change in validity when you call the CURL code again and again. Once you have a long lived access token and you call the CURL code, there wont be any change in the access token. Only the validity of the access token will extend.
Hi Tebe,
Oh I see, so what I do is the correct way to extend the access token? or do you have any other method to solve this problems?
You are using the right method to extend the validity.
Hi Tebe,
it’s me again, I finally know what you means, when you are using the URL below to exchange the facebook token, you need to call your existing token.
https://graph.facebook.com/oauth/access_token?client_id=404741xxxx86356&client_secret=b4a95e6a322xxxxb91515f582461c8c8&grant_type=fb_exchange_token&fb_exchange_token=‘.$access_token;
If the short-lived token is expired, then the URL above cannot be executed correctly, to solve this problem, I just read a paragraph from
https://developers.facebook.com/docs/authentication/access-token-expiration/
which title is “Desktop Web and Mobile Web apps which implement the server-side authentication flow”. It says we need a code and exchange it for a new access token. I don’t know whether my understanding is correct…if yes, could you please teach me how to get the code? thanks.
It’s quite simple.
Just redirect the user to $loginUrl. As we have an already authorized user he will not be prompted to reauthorize your application. That is, he will not see any ‘allow’ or ‘deny’ buttons. $loginUrl will automatically redirect him back to redirect_uri. When the user is redirected back, the url will have GET variable ‘code’ which will be picked by the PHP SDK and new access token will be generated from that.
So, only think that you need to do is to redirect the user to $loginUrl. The rest will be done by Facebook and PHP SDK.
Hi Tebe,
Thanks for your reply, I just saw your reply, just redirect the user to $loginUrl? I understood what you means, but if you do this, new access token will be generated everytime you login, am I right?
could you mind to share me your concept in a simple example, I think it is easily for me to know it clearly, thanks so much.
Fatal error: Class ‘Facebook’ not found in D:\xampp\htdocs\xampp\facebook_testing\fbaccess.php on line 13
i have copied the SDK folder under htdocs but it has this problem. Thanks for your help.
You copied it under ‘htdocs’?? Folder ‘SDK’ or ‘src’ ??
The folder ‘src’ should be under ‘D:\xampp\htdocs\xampp\facebook_testing’
Make sure that module ‘php_curl.dll’ is loaded.
Open ‘php.ini’ and replace:
with
That is, just un-comment (remove semi-colon) the line.
Hello,me again
after a week of good tests i moved my code to my customer host and now it seems that cookies dont want to get saved…basically my user has to click on a login link even if he already gave permissions before,which is quite annoying.i was hoping you have some tip for me also because on my example code in my work host the cookies get saved correctly,so it must be either a host problem or i have no idea what.also i can relate to the guy that gets 0 when he calls getUser(),because thats what i get each time i visit the page after i closed and reopened browser.i also tried to save my own manual cookie containing the user’s facebook id but it seems that the facebook class doesnt like that kind of tricks
You must use client side validation (JavaScript SDK) along with the script to solve this problem.
yep it worked,thanks a lot.I used the code i found here: https://developers.facebook.com/blog/post/534/
@TEBE TENSING: I’m really poor at coding but I’ll like you to please (please!) do me a favour and edit this code to only login users who are members of a specific closed group on Facebook.
Just add the following lines of code to if($user){…} in ‘index.php’
@TEBE TENSING:Thanks Mate….One more thing how do tell it to logout the user instead of echoing something.
@TEBE TENSING
Please how can I make my logout button redirect me back to my login page after logging me out. @ the moment I’m using this code which is an example from ur source file (but in my own case my home page is not together with the login page):
You can use $facebook->destroySession() to force logout of a user from your app. The modified code is shown below.
I’ve tried using your source code file to see how it works following the steps you gave but after logging in it sends me back to the login-in page (index.php) and doesn’t update with the remaining content (images and other stuffs you added inside). I’ve also tried making a new page for it to redirect to instead of index.php but in this case the logout button doesn’t work. Please HELP!
After you login do you still see the login button when using ‘index.php’ as the redirect_uri ??
The logout problem is because of a recent Facebook API change – ‘offline_access Permission Removal’.
Because of the change, by default, an access_token is valid for 60 days. So even if you log out of Facebook your app will remain logged in as the access token doesn’t get expired.
You can use the old API till May 01, 2012 by disabling the ‘Deprecate offline access’ setting from Edit App > Advanced > Migrations tab.
You can read more about it at:
http://developers.facebook.com/roadmap/offline-access-removal/
Hello man
Thanks a lot again your tutorial help me a lot . Now can u do me a little help again ? What I did now I have created my own login system by which user will login and then they will get an option to add facebook . And after authentication process complete users can see their timeline and etc . Like tweetdeck . For this do I need to create a new user table and save auth token and auth secret ? I have saw something like that but I need your suggestion . Also do u have any plan to publish a tutorial for twitter like this also ?
You must save the access token in database. Whenever the user logs in to to your system set the access token from database to Facebook class using:
Also is their any possibility to add like and comment potion ?
To comment on a post with post ID $post_id:
To like an object (posts, comments etc) with object ID $object_id:
@TEBE: Thanks for answering my previous question though I’ve got two more questions to ask.
1) How do you create a comment widget for a group that would allow its members to comment from a website.
2) What would happen to my website if I still have the deprecate access disabled after the 1st of may.
This is a bit urgent……Thanks in advance
Commenting on a Group post is similar to commenting on any other post on Facebook.
On May 1st 2012, offline_access will be depreciated for all Facebook applications. That is, depreciate offline_access will be automatically enabled for all apps.
I guess I phrased the question wrongly. What I meant was “How would you redirect all post/comments made on the website to a specific group page on facebook”
I am not sure of it..
What about if i need to invite friends to like the web page , how can i send the requests to friends.
Use client-side Facebook Javascript API for inviting friends.
Can you please share any example code ?
hello man . In one comment you showed how to implement comment ? and it worked perfectly. But how I can show those comments ? Is there any way to show those as facebook ?
Also I want user to login in my site and then they can add facebook or twitter in the home . I have already created a user table for users login to my site . Do I need to create a seperate table for them to save their accesstoken and fb login details ? U suppose to give a post about it with database intigration . You said in a comment
Thanks
You will need to save the Facebook user ID and access token in database. Then, with the access token you can get any details of the particular user including comments.
I didn’t get time to write a tutorial on database integration.
thanks a lot man . U r just too much helpful . I want to show you something . Can you help me ? Can I pm u or anything ?
hi Tebe…
Thank you very much for your great tutorial…
It helped me to solve a problem which i had for a long time..
I have a small issue now. I want to save the user’s email address in my database for some other tasks.. Can you please tell me how to retrieve the email address.. I tried $user_info['email'] but it’s not working.. Can you please help me with this issue.. Thanks in advance..
Ask for ‘email’ permission and you will get the email in $user_info['email']
Hello,
the log out link does not work …
is there any solution / script change that a user is directly logged out after clicking the button?
best greetings
The logout problem is because of Facebook API change.
Follow the steps to solve the issue:
In index.php replace:
with
Then add a file ‘logout.php’ with the script below.
How the example code so that when users login to fb connect them automatically like the pages that we set?
There is no way to like a Page without user clicking the like button.
You can make a user like a post, comment, photo etc with graph API and the appropriate permissions, but cannot do it with ‘top level’ objects like Pages, websites or URLs.
I was looking for batch requests and it works absolutely fine. Thanks for posting. I have a question.
Will you guide me the right step for:
Lets say I have access to read_friendslist & friends_games_activity. Now I want to query each friend to check if they play a certain game and if yes extract the score. I am able to do it one by one running in a loop.
//$user_friends_list gets the array of all friends.
foreach($user_friends_list as $friends){
foreach($friends as $friend){
// code to check each one by one
}
}
Some people have around 1000 friends and it may take time plus so many continous request to facebook server. Any way I can convert it into a batch request.
Plz ignore my previous comment. I have found a way to address that.
There’s another problem I am facing. Kindly guide.
Assuming I am login with facebook on my site. I open a facbook page in a new tab and logout from there. Now when I click any link on my site an error is generated. The error log says:
“CSRF state token does not match one provided.”
This happens only for the first link clicked on my site if user logout’s from facebook not using my site.
I am not using any database or session to save any data.
There can be several reasons for this error. So I cannot exactly tell the problem without seeing the code.
Once you login to your app, the url will be something similar to:
The ‘code’ and ‘state’ GET variables are needed only once. So please try reloading the page without GET variables just after the authenticated login. It may solve your issue.
Its like you read my mind! You appear to know so much about this, like
you wrote the book in it or something. I think that you can
do with some pics to drive the message home a little bit, but other than that, this
is wonderful blog. A fantastic read. I will certainly be back.
Good answers in return of this query with firm arguments and explaining everything regarding that.
Thanks Man, It helped me a lot.. \m/
Keep flooding the knowledge.
i have this error Facebook not found even if i copied facebook and base_facebook into src
Make sure that module ‘php_curl.dll’ is loaded.
Open ‘php.ini’ and replace:
with
That is, just un-comment (remove semi-colon) the line.
Something like this came out.
Warning: session_start() [function.session-start]: Cannot send session cookie – headers already sent by (output started at C:\xampp\htdocs\drop\index.php:9) in C:\xampp\htdocs\drop\src\facebook.php on line 37
Warning: session_start() [function.session-start]: Cannot send session cache limiter – headers already sent (output started at C:\xampp\htdocs\drop\index.php:9) in C:\xampp\htdocs\drop\src\facebook.php on line 37
session.save_path is uncommented still the problem shows. Please help.
Make sure that you don’t add any html or print anything before the
statement. It should preferably be the first statement.
My partner and I stumbled over here from a different web page and thought I may as well check things out.
I like what I see so i am just following you.
Look forward to exploring your web page again.
i cant make it work
error message:
Fatal error: Class ‘Facebook’ not found in C:\xampp\htdocs\fbk\fbaccess.php on line 13
Make sure that module ‘php_curl.dll’ is loaded.
Open ‘php.ini’ and replace:
with
That is, just un-comment (remove semi-colon) the line.
could you please help me, for integrating it in my local area network. What changes have to do , work it my LAN.
This script should probably work at LAN with an internet connection, though, I am not sure if it.
it is geeting this kind of error:
Uncaught exception ‘Exception’ with message ‘Facebook needs the CURL PHP extension.’ in C:\xampp\htdocs\123\src\base_facebook.php:19 Stack trace: #0 C:\xampp\htdocs\123\src\facebook.php(18): include_once() #1 C:\xampp\htdocs\123\fbaccess.php(8): include_once(‘C:\xampp\htdocs…’) #2 C:\xampp\htdocs\123\index.php(2): require(‘C:\xampp\htdocs…’) #3 {main} thrown in
Open ‘php.ini’ and replace:
with
That is, just un-comment (remove semi-colon) the line.
I really appreciate you posting this tutorial and i really commend your knowledge,please am through with fbaccess.php and am able to include fbaccess.php in index.php and d loginUrl and logoutUrl is also there.I tried my best showing Name,Email and Picture but the problem i have is how to show the status update of each uses and how to update their status through my website,i will be grateful if u can give me d full code of this.THANKS
Basically a post on wall with only ‘message’ field is known as status update.
And the latest posts from a user can be retrieved via:
To post on a user’s wall use:
If you remove all the fields except ‘message’ then it will be called status update.
Thanks for your quick reply,am sorry,am a newbie in php,pls i have two questions to ask
1)am i to just copy and paste the above code you gave me in index.php?
,because to retrieve the posts,its already in fbaccess.php and its included in index.php ,do i need to rewrite it in index.php and
2)for example to get user name and email i would just write it like this
So to view status update will just put
Please enlight me, or can you please give me the full code i can put in my index.php
THANKS
Hi .
Thank you very much for your tutorial ,really nice ,Thank a lot once again perfectly working ….
after click logout buttion not redirect to my site or logout buttion is not working
after click logout buttion not redirect to my site or logout buttion is not working ——————-
The logout problem is because of Facebook API change.
I have commented the fix for this above.
Please find it at:
http://25labs.com/tutorial-integrate-facebook-connect-to-your-website-using-php-sdk-v-3-x-x-which-uses-graph-api/#comment-1239
Hi ,I have an issuse ,Once close the mozila browser ,next time i need to give login detail for facebook once again,is this possible stay connected even after close the browser ?
hey i got annswer from your previous replies anyhow thanks a lot
hi ,I have doubt regarding privacy settings ,is it possible to set the privacy as “public” and particular friendliest for feed post ,please let me know ,thank you….
sujith
my proplem is not solved mannn please send me the solution by mail
arabic is not working why why
man i need your urgent help ,my fb post working well no problem ,eg file name publish.php ,if i use the same file in crontab to execute through ssh ,it return error “OAuthException: (#803) Some of the aliases you requested do not exist: 0 ” please give me an idea
hey really like ur tutorial but i’ll try it after 8 or 9 0 clock
i don’t know about webhosting means i em not proffessional in html ..etc
plz tell me i what i have to write in front of scope ? in step 8 plz quick reply
at the end of my redirect url, i get some parameters like ?state=something&code=……..
How can i remove it from my redirect url?
Hi, for some reason the getUser() method is always returning 0
does anybody know why?
hello yr.. nice tutorial..
i wanted to know more about the index.php page you created and how to access information facebook sends to us…
thankx ,
if possible please do reply immediately
You don’t have permission to access /source/< on this server.,,how to solve this..i'm running this on my localhost..and one more thing..pls tell me …in the website url what i will write??? i shoulh b like this hhtp:localhost or something else….
Your style is unique in comparison to other folks I have read stuff from.
I appreciate you for posting when you’ve got the opportunity, Guess I’ll just bookmark
this site.
Include of “facebook.php” is not working. It stops the entire php stop running. When I checked in log files ” it showing 500 error. Can anyone provide help to me to comeout of this error.
hello i have a problem with your code, it´s do the “connect” perfectly, but only show me a litle information, just de name and username, no photos, no info, no feed,…. any ideas?
Here my error log! can you help me what’s wrong? thx
PHP Parse error: syntax error, unexpected ‘[‘ in /home/chucap/public_html/fbfinal/index.php on line 147
Wonderful, what a web site it is! This blog provides helpful information
to us, keep it up.
i would like to ask u that i want to use localhost but when i write localhost in domain name input box on facebook apps page then a error is occured .The error is
{Error
You have specified an App Domains but have not specified a Site URL or a Mobile Site URL
localhost must be derived from your Site URL or your Mobile Site URL.
}
could u please give me a example of how to put localhost in that input.
thankyou
Hi Mazhar,
I had the same prob so i did it like this:
app domains: localhost;
site URL: http://localhost/folder-name/
I am not sure about the solution, coz now i m facing some other issues..
hope it works for u.. good luck..
First of all: Thank you so much for this script! Awesome stuff.
Now my question: I succeeded in getting the user logged in to my FB app, but I cannot figure out how to automatically create a new user in the wordpress site I have implemented your above script in. So once the user logs in with Facebook I want a new wordpress user to be created automatically.
I followed the wordpress documentation on how to create a new user via the function wp_insert_user, but I am missing something.
Here is what I did:
1. Put the declaration of wp_insert_user into a new file
2. Included that new file into the wordpress page where my users login with Facebook
3. Inserted wp_insert_user function on the same wordpress page like this:
getUser();
// We may or may not have this data based on whether the user is logged in.
//
// If we have a $user id here, it means we know the user is logged into
// Facebook, but we don’t know if the access token is valid. An access
// token is invalid if the user logged out of Facebook.
if ($user) {
try {
// Proceed knowing you have a logged in user who’s authenticated.
$user_profile = $facebook->api(‘/me’);
} catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
}
$user_id = 1;
$website = ‘http://wordpress.org’;
wp_insert_user( array (‘ID’ => $user_id, ‘user_url’ => $website) ) ;
$user_id = 1;
$website = ‘http://wordpress.org’;
wp_insert_user( array (‘ID’ => $user_id, ‘user_url’ => $website) ) ;
…
I think the trouble is that I don’t know where to put the wp_include_user function so that it actually works. Otherwise no error messages.
Here is some wordpress info: http://codex.wordpress.org/Function_Reference/wp_insert_user
Thank you in advance!
Florian
I should mention that the wp_insert_user function used in the example above only updates a user field. So it is just for testing if the function works.
Something I don’t understand right now, have it all working but getting too much data from a FB user. Don’t need to know his entiry work/employment stuff.
So I deleted read_stream from scope.
Still it gives me everything.
What can I do to narrow all things down to getting this info only:
id, user full name, email
?
Wonderful blog! I found it while surfing around on Yahoo News.
Do you have any tips on how to get listed in Yahoo News?
I’ve been trying for a while but I never seem to get there! Cheers
very very helpful, Thanks.
I have made an application in facebook and it works fine but sometimes it shows fatal error on the line 1128 in the base_facebook.php file when some users try to open it.
what could be the cause of the error? and how can I solve it?
Thanks in advance.
API Error Code: 191
API Error Description: The specified URL is not owned by the application
Error Message: Invalid redirect_uri: Given URL is not allowed by the Application configuration.
please give me solution for this error…
This code really helped me a lot
but what i am trying now is my app should send request to all the friends in my list and send notification for the events that i create from this app.
Hi,
Thanks for the great solution. I was able to implement it, but I’m stuck on a small annoying bug.
When you first log in (or after you log out and try to log in again) each time you get to my site, it displays the page which is for an unlogged in user. Once you press ‘login’ again it works.
Is anyone able to give me any ideas?
Site is:
http://www.kaha.biz/7/dev/index.php
Hi,
Just an update. I realised that somehow I had implemented bits and pieces of code from different files. I started from scratch and when it came together it worked perfectly.
The site is now live if anyone is interested in checking it out.
http://www.kaha.biz
Cheers
Peter
Terrific post but I was wanting to know if you could write a litte
more on this subject? I’d be very thankful if you could elaborate a little bit further. Many thanks!
Hi,
thanks a lot for the tutorial, it was easy to implement ur codes.. but i hav a problem:
Fatal error: Class ‘Facebook’ not found in C:\wamp\www\source\fbaccess.php on line 13.
So I disabled the comment before ;extension=php_curl.dll in php.ini
and also set session.save_path = “c:/wamp/tmp”.
but still its not working.. ur help would be highly appreciable..
ty..
Hi,
Did you find an answer on your problem?
I’ve exactly the same problem.
Hi, I implemented you tutorial on my joomla site, my problem is how to add joomla session when user was logged in. Many thanks
hello
This is very useful tutorial. But i have a problem when a user logged in how to send (or) add in to session stating that user logged in. In my site the page from login is not redirecting to another page. [lease help me
Is there any way that I can make it do automated post like repeat a post or schedule?
Hello sir! Great tutorial. But i’m not sure about how i could intregate this into my website. I want to use the Facebook login as an alternative method to log into my Game. How do i do this? Sorry I’m a novice.
You could certainly see your expertise in the paintings you write. The sector hopes for even more passionate writers like you who are not afraid to mention how they believe. All the time follow your heart.
Wonderful website. A lot of useful info here. I am
sending it to a few buddies ans also sharing in delicious.
And naturally, thanks for your sweat!
hey Tebe, Thanks first of all. keep gng.
I just need to ask how can I get
$user_info['email'] and mobile no.. I am able to fetch
everthing except email and mobile no…..
please help me out or Is it unaccesible due to security purposes..
rep will be appreciable.
Hey, great extension, this is great but I have one question.
I was to simplify it so they only post to one group. But when I check out the index page (copied from example just replaced the api info), I dont see groups.
http://letsgoexchange.com/fb/index.php
I added my own group there manually and the group ID is valid (checked it in facebook) but when I post it doesnt actually work.
Any suggestions?
Thanks
IT’S WORK 100%
THANKKKKK YOUUUU BROOOOOTHER!!
A person necessarily help to make seriously posts I might state. This is the very first time I frequented your website page and so far? I amazed with the analysis you made to create this actual put up amazing. Fantastic process!
thanx for sharing…
If any one is having problems logging users out, use this
if(isset($_GET['logout'])=='1'){
if (isset($_SESSION['fb_' . $app_id . '_code'])) {
unset ($_SESSION['fb_' . $app_id . '_code']);
}
if (isset($_SESSION['fb_' . $app_id . '_access_token'])) {
unset ($_SESSION['fb_' . $app_id . '_access_token']);
}
if (isset($_SESSION['fb_' . $app_id . '_user_id'])) {
unset ($_SESSION['fb_' . $app_id . '_user_id']);
}
and this would be what you would use in your fbaccess.php
$logoutUrl = $facebook->getLogoutUrl(array(
'next' => 'http://..../login.php?logout=1', // URL to which to redirect the user after logging out
));
Hi, I do believe this is a great website. I stumbledupon it
I may return once again since i have saved as a favorite it.
Money and freedom is the greatest way to change, may you be rich and continue to guide others.
I got following error
Invalid or no certificate authority found, using bundled information
Please reply me how to solve it
Pretty nice post. I just stumbled upon your weblog
and wished to mention that I’ve really loved surfing around your blog posts. In any case I will be subscribing to your rss feed and I hope you write once more soon!
This is a brilliant tutorial and very well supported. The only thing missing (from my perspective) is database connection
Keep the tutorials coming. Thanks!
Thanks
Hello there! I simply want to give you a huge thumbs up for your great
info you have here on this post. I will be returning to your web site for more soon.
sir i wanna use login with fb in my website than how i can do so.what is the procedure to do such.tell me sir
Hi,
the get “getUser returns always 0″ error will be fixed with updating to the newest “./src/fb_ca_chain_bundle.crt”, because Curl will return an ssl error (the facebook class doesnt echo it…)
have fun
Here my error log!
(Error code: ssl_error_rx_record_too_long)
can you help me what’s wrong?
Greetings! This is my first comment here so I just wanted to give a quick shout out and tell you I genuinely enjoy reading your articles.
Can you suggest any other blogs/websites/forums that deal
with the same topics? Thank you!
You area great !
Thank you very much for this
just i have 1 problem and i try to find solution for it :
If the visitor is trying to login but he is not register to my APP
facebook will redirect him to example.php page without asking him to accept my App and register
in other words i only need to let my current user to path from the Fblogin url and if he
not a user then i will redirect him to other page without asking hem to register for my App
Could anyone help me please ?
Thanks
my status updates are all failing when i implement your code. they are getting caught at the FacebookApiException of the pub, and status posts.
my error is returning tho echo “fail ” . $user_info['first_name'];
I’m really enjoying the theme/design of your weblog. Do you ever run into any web browser compatibility issues? A number of my blog visitors have complained about my blog not operating correctly in Explorer but looks great in Chrome. Do you have any tips to help fix this problem?
I will immediately seize your rss feed as I can’t in finding your email subscription link or newsletter service. Do you have any? Kindly permit me understand in order that I could subscribe. Thanks.
Pretty nice post. I just stumbled upon your weblog
and wanted to say that I have truly enjoyed surfing around your blog posts.
After all I’ll be subscribing to your rss feed and I hope you write again very soon!
Very good info. Lucky me I recently found your blog by accident (stumbleupon). I have book marked it for later!
Quality posts is the important to be a focus for the people
to pay a quick visit the website, that’s what this web page is providing.
Great job bro!
Hi, I created a popup with your code to login with facebook.
If i press the button he ask me for permission which is good.
Next i return back automatically to my website: http://localhost/cms4/ with a huge &_GET params:
?state=c238e19274e15053d3f94ba38c384b2a&code=AQCrOXc41aImr_UYuxT4Lsn0Z8c7vLE2FHybbDZkEnsMiCd1by8202-pPLQ2X40mG5osNetXycT9IuXmd_9dl0lbbA4khaG41lVAr5Ya_QN5fEffIuROa2BoW2p-utzfY3nZ36KfUJarM4TfN7MINZqRtTdSD7kNOqKgUqaQrv-IFRZXMFk5zKKFfeY0rNtoVOLn2-u4UNPwlPnsRnZxPa-H#_=_
still i’m not logged. Do i something wrong?
Pretty section of content. I just stumbled
upon your weblog and in accession capital to assert that I acquire actually enjoyed
account your blog posts. Anyway I will be subscribing to your augment
and even I achievement you access consistently fast.
You are a awfully intelligent person!
Please help me out.
Ive done the changes as youve said but unfortunately what happens is after authenticating and entering my Fb details instead of going to the app page which displays the freinds images and all i get returned back to the same login page with the button. Please help its urgent.
Will be verythankful
Hey, awesome tutorial! I created an app that posting on user’s facebook wall when he clicks ‘facebook connect’ button. But my question is: Is there possible to post on users’ walls anytime?
Let me explain what I mean. Here’s what my app does at the moment:
- user clicks ‘facebook connect’ button
- he’s redirected to page where he can allow my app to retrieve his info and post on his wall
- he clicks ‘allow’ and my app posts a message on his facebook wall
Now, I’m trying to find some piece of code or script allowing me do this:
- I would have some textarea to write a message and then button below to post the message on facebook walls of all users, who clicked ‘facebook connect’ button on my website and allowed my app posting on their walls.
I checked dozens of tutorials trying to find how to do it, but I can’t find anything. I would really appreciate your help. Thanks a lot!
Hi, it’s a nice tutorial
but I get the error,
Fatal error: Class ‘Facebook’ not found in C:\xampp\htdocs\facebook\fbaccess.php on line 13
I have all change done in php.ini file but i cant understand where i put php sdk.
Valuable information. Lucky me I discovered your web site by accident, and I’m shocked why this coincidence didn’t took place earlier! I bookmarked it.
I am tryning to login the user into my websyt using this……the login URL does redirect me to facebook……and i am redirected to my home page but the $user remains 0 and user_info array is still unintialised
Plz help
[13-Jan-2013 05:05:58] Invalid or no certificate authority found, using bundled information
I am getting this error in my php error
log
What’s up to every body, it’s my first pay a quick visit of this webpage; this webpage contains awesome and actually
good information in favor of visitors.
how can we use it on free hosting sites
How I can retrieve City, State and country in separate variable to insert into db ?
Please help me out, I cannot make a button through which users will click and accept the facebook dialog box and get logged in, I have successfully made the fbaccess.php file and also linked src/facebook.php
I do not leave many remarks, however after reading a great
And, if you are writing on other places, I’d like to follow you.
deal of remarks on Tutorial: Integrate Facebook Connect
to your website using PHP SDK v.3.x.x which uses Graph API | 25 labs.
I do have 2 questions for you if it’s okay. Is it only me or does it look like some of the remarks look as if they are coming from brain dead visitors?
Could you make a list of every one of all your social community sites like your twitter feed, Facebook page or
linkedin profile?
Does this tutorial works on fb now ? because in my experience there is an sandbox mode when enabled admin only can see the posts, disabled mode only works on SSL certified domains.. any idea on this ? please let us know, thanks for sharing
Hey this tutorial was really handy and useful to me.Thanks a lot
There is an issue ,pls help me.
Its working fine in localhost,but when i try to access the same in other system/mobile using my IP address(same wifi/lan) it says “some error occured and redirects to original fb page…
Please help me out.
How to show welcum message on the script
“Tutorial: Integrate Facebook Connect to your website
using PHP SDK v.3.x.x which uses Graph API | 25 labs” actually causes me personally
think a little bit further. I really adored every individual element of this blog
post. Thanks for your effort -Raymon
Before Login to facebook following error come:
—————————————————–
Error
_____________________________________________________
An error occurred. Please try again later.
_____________________________________________________
After Login to facebook following error come:
—————————————————–
Error
_____________________________________________________
An error occurred. Please try again later.
_____________________________________________________
API Error Code: 191
API Error Description: The specified URL is not owned by the application
Error Message: Invalid redirect_uri: Given URL is not allowed by the Application configuration.
This Guy is making money with this App
http://fb.maherhackers.com/
It worked. PHP SDK link needs to be updated. Thanks for the tutorial.
can not login .. when I login, login page to repeat the same
i got the same error…
Hi, Nice code. I tried it on my site, it worked once and started giving this error CSRF state token does not match one provided.
I am running this code from a sub folder called http://www.mydomain.com/fb
same issue..Fatal error: Class ‘Facebook’ not found in C:\xampp\htdocs\facebook-exp\sdk\source\fbaccess.php on line 13..how to deal with this error.
n where to put php.ini.
php.ini is not there in downloaded folder.
plz revert ASAP.
My only problem was logout call then realized that browser (Chrome) was storing all data so it appeared with just print_r($profileData) as though user wasn’t being logged out as information was just being shown from Chrome’s local cache.
Might be a problem of others if logout doesn’t work. Why doesn’t fb produce easy to understand guides to their APIs? Maybe they should call you. Reminder to self: Chrome for development is no Firefox.
I tried everything step by step. here is what i get when i go to my website.
‘appId’ => $app_id, ‘secret’ => $app_secret, )); $user = $facebook->getUser(); if($user){ //==================== Single query method ====================================== try{ // Proceed knowing you have a logged in user who’s authenticated. $user_profile = $facebook->api(‘/me’); }catch(FacebookApiException $e){ error_log($e); $user = NULL; } //==================== Single query method ends ================================= } if($user){ // Get logout URL $logoutUrl = $facebook->getLogoutUrl(); }else{ // Get login URL $loginUrl = $facebook->getLoginUrl(array( ‘scope’ => ‘read_stream, publish_stream, user_birthday, user_location, user_work_history, user_hometown, user_photos’, )); } try{ $user_info = $facebook->api(‘/’ . $user); $feed = $facebook->api(‘/’ . $user . ‘/home?limit=50′); $friends_list = $facebook->api(‘/’ . $user . ‘/friends’); $photos = $facebook->api(‘/’ . $user . ‘/photos?limit=6′); }catch(FacebookApiException $e){ error_log($e); } //========= Batch requests over the Facebook Graph API using the PHP-SDK ======== // Save your method calls into an array $queries = array( array(‘method’ => ‘GET’, ‘relative_url’ => ‘/’.$user), array(‘method’ => ‘GET’, ‘relative_url’ => ‘/’.$user.’/home?limit=50′), array(‘method’ => ‘GET’, ‘relative_url’ => ‘/’.$user.’/friends’), array(‘method’ => ‘GET’, ‘relative_url’ => ‘/’.$user.’/photos?limit=6′), ); // POST your queries to the batch endpoint on the graph. try{ $batchResponse = $facebook->api(‘?batch=’.json_encode($queries), ‘POST’); }catch(Exception $o){ error_log($o); } //Return values are indexed in order of the original array, content is in ['body'] as a JSON //string. Decode for use as a PHP array. $user_info = json_decode($batchResponse[0]['body'], TRUE); $feed = json_decode($batchResponse[1]['body'], TRUE); $friends_list = json_decode($batchResponse[2]['body'], TRUE); $photos = json_decode($batchResponse[3]['body'], TRUE); //========= Batch requests over the Facebook Graph API using the PHP-SDK ends ===== try{ $statusUpdate = $facebook->api(“/$user/feed”, ‘post’, array(‘message’=> ‘Your Status goes here’)); }catch(FacebookApiException $e){ error_log($e); }
Welcome to my home page!
Some text.
Im getting this error now trying to run the facebook login.
Warning: include(fbaccess.php) [function.include]: failed to open stream: No such file or directory in /home/content/55/10548855/html/index.php on line 4
Warning: include() [function.include]: Failed opening ‘fbaccess.php’ for inclusion (include_path=’.:/usr/local/php5_3/lib/php’) in /home/content/55/10548855/html/index.php on line 4
Welcome to my home page!
Some text.
Does anyone know what caused this problem??
Anytime I make a change to index.php it throws Warning: session_start() [function.session-start]: Cannot send session cache limiter – headers already sent (output started at /home/speak/public_html/newfacebook/index.php:1) in /home/speak/public_html/newfacebook/src/facebook.php on line 37.
If I go back to the original index.php it works fine. Any suggestions?
Where is the “Create New App” button
? I did not find such a button.
Hi.Thanks for your tutorial.But it didn’t work on my localhost. it shows error : Fatal error: Class ‘Facebook’ not found in E:\wamp\www\facebook-connect\fbconnect.php on line 15.
I have un-comment extension=php_curl.dll. But it still not working… Could you help ? Thanks.
Is it hard to get their email? I know they have to agree and all that but not sure what the code is to access this. I have not tried it but just wondering. Thanks
pls heip me im getting tis type f error while implementing facebook login to my site
Fatal error: Uncaught exception ‘Exception’ with message ‘Facebook needs the CURL PHP extension.’ in D:\wamp\www\source\src\base_facebook.php on line 19
( ! ) Exception: Facebook needs the CURL PHP extension. in D:\wamp\www\source\src\base_facebook.php on line 19
Just uncomment the line ;extension=php_curl.dll in php.ini. Means remove (;) like extension=php_curl.dll and restart all service.
I have received this issue.Can you look and guide me.
Parse error: syntax error, unexpected ‘public’ (T_PUBLIC) in C:\wamp\www\FB\src\facebook.php on line 50
Thank you
How posible random friends show in this code
Friends ()
10) break;
}
?>
Works great! Thanks man! It was hard to find a tutorial that good. Congratz!
Hello are using WordPress for your site platform?
I’m new to the blog world but I’m trying to get started and create my own.
Do you need any coding expertise to make your
own blog? Any help would be greatly appreciated!
I wanted to inform you for this great help!! I definitely enjoyed every little bit of it.
I REALLY need some help setting this up. I can pay someone for their time.
Any takers?
hi,
1) i have set session.save_path = “/home/vijay/Documents/workspace-helios/EdVie_Moodle/fb_connect/session_data/” in php.ini
2)i have un-commented extension=php_curl.dll
still im getting facebook->getUser() as 0 .it used to wokk about a week ago after which i lost the code and i reconfigured every thing and now its not working .
please help i have tried and tried all resorts possible .
Flow
1)connect to facebook button
2)FB login screen
3)app allow access screen
4)redirected to a page where getUser says 0
i also wanted to ask if the session path needs to point to a file or just a directory .
Thanks for the good writeup. It in reality was a entertainment account it.
Glance advanced to far delivered agreeable from you! By the way,
how could we keep in touch?
This warning occurs when i run my code. everything display so very fine except user feed details. Kindly help..!!
Warning: Invalid argument supplied for foreach() in source/index.php on line 291.
289. News Feed
290. <?php
291. foreach($feed['data'] as $news)
292. {
293. $pro_pic = 'https://graph.facebook.com/'.$news['from']['id'].'/picture';
294. $from = $news['from']['name'];
295. $time = $news['created_time'];
its not working its redirecting me to same login page please help
Hi,
Thanks for your great tutorial.
I am trying to implement your fb login in my site.Everything is ok means no error is generated but here my problem is that it always return 0 in $userid. I have setup login and logout url as you mentioned in tutorial and when I click on login url It redirect me on facebook login and when I type email and password and hit submit button it redirect to my local site but when I am printing $userid it return zero everytime. Please help to solve this problem.
I either missed this, or… My Login button always responds with:
https://mydomain.com/facebook/%3C?=$loginUrl?%3E
Seems this loginUrl is not being set.
Any ideas where I missed this? I’ve made no custom changes other than what is mentioned about to set this up.
can u please tell me how to get email of the logged user in fb using fb connect ?
Hi tebe,
I implemented the codes but whenever i’m clicking the connect button, i’m getting “An error occurred.Please try again later.”
Can you fix this ??
hi i used above program works fine but my question is that after logged in through facebook in a website i want to use logout also in my site now loggin in my website nice what about logout