How to Login with Facebook Graph API in PHP
I have been working on facebook apps and connection with Facebook Graph API access tocken. This post will explain you how to integrate facebook connect in your website in easy way to connect and read the Facebook home timeline with PHP. Explained how to get facebook token and user id hope you like it. Thanks !
Make New Application on Facebook:
1. Visit https://developers.facebook.com/apps and click + Create New App.
The script contains two folders called oAuth and images with PHP files.
src
– base_facebook.php // Class Get user Info
– facebook.php // Class Get user Info
– config.php // Configuration file
images
html.inc // html design view
index.php // Main index file show data
PHP Code
Edit config.php
<?php $config['callback_url'] = 'CALL BACK URL/?fbTrue=true'; // /?fbTrue=true allow you to code process section. //Facebook configuration $config['App_ID'] = 'Your App ID'; $config['App_Secret'] = 'Your App Secret'; ?>
Index.php
While clicking Login with Facebook button URL requesting Facebook Graph API with contains your web project redirection URL:
$config['callback_url'] = "http://www.yoursite.com/index.php/?fbTrue=true"; // added in config.php
.
<a href="https://www.facebook.com/dialog/oauth?client_id='.$config['App_ID'].'&redirect_uri='.$config['callback_url'].'&scope=email,user_likes,publish_stream"><img src="./images/login-button.png" alt="Sign in with Facebook"/></a>
<?php require 'src/config.php'; require 'src/facebook.php'; // Create our Application instance (replace this with your appId and secret). $facebook = new Facebook(array( 'appId' => $config['App_ID'], 'secret' => $config['App_Secret'], 'cookie' => true )); if(isset($_GET['fbTrue'])) { $token_url = "https://graph.facebook.com/oauth/access_token?" . "client_id=".$config['App_ID']."&redirect_uri=" . urlencode($config['callback_url']) . "&client_secret=".$config['App_Secret']."&code=" . $_GET['code']; $response = file_get_contents($token_url); $params = null; parse_str($response, $params); $graph_url = "https://graph.facebook.com/me?access_token=" . $params['access_token']; $user = json_decode(file_get_contents($graph_url)); $content = $user; } else { $content = '<a href="https://www.facebook.com/dialog/oauth?client_id='.$config['App_ID'].'&redirect_uri='.$config['callback_url'].'&scope=email,user_likes,publish_stream"><img src="./images/login-button.png" alt="Sign in with Facebook"/></a>'; } include('html.inc');
Next Tutorial on Google Login.
Tutorial Categories:
Very nice topic. It is very useful for Facebook Group API in PHP programming.
not working
here’s my app http://demo.phpgang.com
Some thing is wrong in your code application working fine and returning with code.
FROM WHICH PAGE WE CAN GET THE USER DEATAILS IN FACEBOOK API??
AND HOW TO POST THE USER DEATILS INTO DATABASE OR PARTICULAR PAGE???
Check code in index.php for data.
if(isset($_GET[‘fbTrue’]))
{
$token_url = “https://graph.facebook.com/oauth/access_token?”
. “client_id=”.$config[‘App_ID’].”&redirect_uri=” . urlencode($config[‘callback_url’])
. “&client_secret=”.$config[‘App_Secret’].”&code=” . $_GET[‘code’];
$response = file_get_contents($token_url);
$params = null;
parse_str($response, $params);
$graph_url = “https://graph.facebook.com/me?access_token=”
. $params[‘access_token’];
$user = json_decode(file_get_contents($graph_url));
$content = $user;
}
I’m not worthy, I’M NOT WORTHY! Oh, great and powerful Facebook wizard, you are the first person — THE FIRST PERSON — who has actually published a functional example of a Facebook authentication chain!
I’ve been struggling with this and other problems with the Facebook API for an *ENTIRE YEAR* — an entire year!
I start on trying to solve the problem, and then I stop for a while, out of frustration.
Can you please recommend the reference materials (books? e-books?) that you used to figure this out???? Also, please consider writing and publishing your own book on the subject. I’ll be the first to buy it!
Thank you, so much!
I am not getting user details however login with facebook working properly what whould be the problem….
Use exact given demo code might be you are making some mistake or edit something in it please recheck your code or paste it here.
Many thanks, again to Huzoor Bux. I’ve made a few changes to the procedure described, herein, and outline them in a blog entry of my own: http://wexblog.prwexler.com/2013/04/11/a-simple-facebook-authentication-chain.aspx
Hello, I cannot download this. It keeps saying im not subscribed although i already am. Please help
@hyipboxcom:disqus you are in list now please download code.
It keeps saying im not subscribed although i already am. Please help
Hi. i use your code but the content is not showing. please help me.
This code is working perfect make sure that your application is not on sandbox mode make it on live mode and try again. Please debugg your code and send me exact error or paste your code here.
I have found error there is a mistake in tutorial edit your config.php and add “fbTrue=true” like below.
$config[‘callback_url’] = ‘http://demo.phpgang.com/facebook_login_graph_api/?fbTrue=true’;
let me know if you are facing any error.
Warning: file_get_contents(https://graph.facebook.com/oauth/access_token?client_id=644757838891317&redirect_uri=http%3A%2F%2Fohchoky.com%2Fbooking2%2Ftravel%2Findex.php%3FfbTrue%3Dtrue&client_secret=72f029de15fea6151ec4387ca8873599&code=AQAei9LOUPwhyQ_ar0n6HoYbtjkCW2Y4ADM2UVsuWMjGlvU0pKII5E3JyoMZeGGLzqKUS5LbJXyHyiZeDBxF91yt8eXnxuHuBpe3ofrzwoY5R24761PHxf3m_b3oJAXlGbr6Wyf414Uy1oDFke1f4Q5C87YlPrwmWIuqjuSOQERfNb6k47ESRy1buqPuESSqMb3xPA1NFQkziU3UGFR-ioY4y_YMSlRihp3-oDKvmKuOwx9JOp4FWQ5P2qk-wSAwBDitAuo6qnfrV7hAbP0BiAidqM-m4qvMzbtS7rcgnXCEO0RoDIB46-8zkaVFF_55MF0) [function.file-get-contents]: failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request inD:Hosting10958518htmlbooking2travelindex.phpon line 202
Warning: file_get_contents(https://graph.facebook.com/me?access_token=) [function.file-get-contents]: failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request inD:Hosting10958518htmlbooking2travelindex.phpon line 208
file_get_contents will only work if you have allow_url_fopen = 1 in your php.ini
For remote file access like above, consider using the cURL functions that PHP provides.
function url_get_contents ($Url) {
if (!function_exists(‘curl_init’)){
die(‘CURL is not installed!’);
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $Url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); //get the code of request
curl_close($ch);
if($httpCode == 400)
return ‘No donuts for you.’;
if($httpCode == 200) //is ok?
return $output;
}
So sir what i have to do in this code please help me?
Edit your php.ini or use cURL insted of file_open-content function. Tutorial on how to Replace file_get_contents/fopen with cURL: https://www.phpgang.com/replace-file_get_contentsfopen-with-curl_30.html.
hello
pls help have url
$response = file_get_contents($token_url);
$user = json_decode(file_get_contents($graph_url))
hello sir , this code is not working.its returning..http://ohchoky.com/booking2/travel/index.php?code=…….
Can you provide code for logout from site..?
Script is updated and below is the for log out from fb. You can also download complete code or you can check in our demo for testing.
$url = ‘https://www.facebook.com/logout.php?next=’ . urlencode(‘http://demo.phpgang.com/facebook_login_graph_api/’) .
‘&access_token=’.$_GET[‘tocken’];
session_destroy();
header(‘Location: ‘.$url);
it appear to have long URL after the user have logged in..
I have a problem when I refresh the page. I lost the data of fb login. Can you help me?
you have to save that data to show after reload.
hello and thanks for the tutorial… its the best I’ve seen so far (been struggling for several days now)… anyway
I have it working, but added this part:
// your code
test_login($config, $facebook) ? validLogin() : userLoginScreen($config);
print “You are logged in!n”;
// the above works, but
//this below causes this error:
//Fatal error: Uncaught OAuthException: An active access token must be used to query information about the current user.
$user_profile = $facebook->api(‘/me’,’GET’);
echo “email: ” . $user_profile[’email’];
====
so where or how do I get the user email’s address?
thanks!
check this code in url https://developers.facebook.com/docs/php/howto/profilewithgraphapi/ and use try catch block when ever you call facebook functions.
When I log in, can hide fbTrue and code from the domain address?
Yes you can store data on session or cookie and redirect without url query strings.
hi sir, i’m getting the following in this script:
Secure Connection Failed
An error occurred during a connection to taurustrip com.
SSL received a record that exceeded the maximum permissible length.
(Error code: ssl_error_rx_record_too_long)
The page you are trying to view cannot be shown because the authenticity of the received data could not be verified.Please contact the website owners to inform them of this problem. Alternatively, use the command found in the help menu to report this broken site.
Share your callback url.
hi sir, this is the callback url you asked. Did i do something wrong in it? please help.
$config[‘callback_url’] = ‘https://taurustrip com/projectjob/facebook_login_graph_api/index.php/?fbTrue=true’;
Your website is not ssl supported please use http:// instead of https:// it will work properly.
I now using http instead of https & script is running now but it is showing me a blank page with coming soon text on the page.
you may see it here:
www{.}taurustrip{.}com/projectjob/facebook_login_graph_api
i now using http instead of https as you told me & script is running now but it is showing me a blank page with text: Coming soon.. instead of logout button.
you may see it here
www{.}taurustrip{.}com/projectjob/facebook_login_graph_api
Hi
i have face following error Please help
Given URL is not allowed by the Application configuration.: One or more of the given URLs is not allowed by the App’s settings. It must match the Website URL or Canvas URL, or the domain must be a subdomain of one of the App’s domains.
same thing happen with me, i have tried to create facebook app with localhost url and registred domain it is “Something went wrong. We’re working on getting it fixed as soon as we can”
You must have a hosted application it will not work properly on localhost.
Thanks for your reply, but it is giving me same error for hosted application also
thank you i will also work on it and fixed it as soon as
You have to add domain on which you are receiving request like in this image.
thank you
i will try it on live
Hello, I cannot download this. It keeps saying i’m not subscribed. Please help
Use exact url instead of only page name.
i tried with that but its not working
is it possible to do the above procedure by just running the web application in localhost ??
Not possible on localhost use some host to do that.
Actually you can run this on local host if you place your localhost/folder url in your app settings/Advanced
Valid OAuth redirect URIs –
How about registering user on local db, using info provided from facebook?
Shit
hello every one can we open it in pop up with responsive facebook
This source was working but the issue was after authentication on facebook it was redirecting to the call back url and displaying nothing can you please help me out
config.php call back url change karo
logout button not visible… can you help me??
everything is done but i’m still at the end . i don’t get any output..is anything a missed apart from this.
turn on errors and try again you might get some error on that page.
hi, Thank you so much.. i will try this
I can’t download your script, even though I subscribed. 🙁
Warning: file_get_contents(https://graph.facebook.com/me?access_token=) [function.file-get-contents]: failed to open stream: HTTP request failed! HTTP/1.1 400 Bad Request in facebook_login_graph_api/index.php on line 33
pls help me
how to get friend list by this api help me..
suscribed but not downloaded why..
hi….i cant get logout link
hi huzoor bux…thanks for such article…can you please help me how to get only the friends name and email address using this code
Hi sir … thanks for share this article, this is really helpful for me. Good job.
sir i have authorization problem in this code
this is showing content in array form
i got a problem:
Warning: file_get_contents(https://graph.facebook.com/me?access_token=): failed to open stream: Connection refused in /home/u504800903/public_html/facebook_login_graph_api/index.php on line 34
I’ve got the same issue, did you find any solution for this Rezky? Thank you
I’ve got the same issue, did you find any solution for this Rezky? Thank you
it logins but then it only displays username & fb id , i wants to display email & logout button too. plz help me bhaijaan.
This is kind of old my friend. Graph API has been updated. To get the email Id you will need to put it in scope parameter..
how to fix the error Given URL is not allowed by the Application configuration: One or more of the given URLs is not allowed by the App’s settings. It must match the Website URL or Canvas URL, or the domain must be a subdomain of one of the App’s domains.
Its Very Simple follow below given steps.
1. Go to ‘Basic’ settings for your app
2. Select ‘Add Platform’
3. Select ‘Website’
4. Put your website URL under ‘Site URL’
See attached image. https://uploads.disquscdn.com/images/2334186b48e4071c1e2a9a7997d85a2f6d9fba8bfaf386147dae2853b7772b00.jpg
Its Very Simple follow below given steps.
1. Go to ‘Basic’ settings for your app
2. Select ‘Add Platform’
3. Select ‘Website’
4. Put your website URL under ‘Site URL’
See attached image. https://uploads.disquscdn.com/images/2334186b48e4071c1e2a9a7997d85a2f6d9fba8bfaf386147dae2853b7772b00.jpg
thank u sir got it
how to get mobile number or email id of people who logged through Facebook into our website
how to get the user info such as mobile number ,email,name people who logged through Facebook into our website ,please help me itz urgent
You can get email by requesting email in scope like this scope=email. Facebook not allowed to get mobile number in api.
i can’t get the email id using this scope=email ,getting only appid and name
Please share link.
$content = ‘‘;
please help me
your website Link please?
https://www.facebook.com/dialog/oauth?client_id=‘.$config[‘App_ID’].’&redirect_uri=’.$config[‘callback_url’].’&scope=email
this is the link $content = ‘‘;
$content = ‘‘;
You can get email by requesting email in scope like this scope=email. Facebook not allowed to get mobile number in api.
hi huzoor bux…thanks for such article…can you please help me how to get only the friends name and email address using this code
.can you please help me how to get only the friends name and email address using this code in facebook login in php
same error .any soultion for this error?
i can only see the id and the name. Why can i not see the location and gender?
Create a rewrite rule.. for php it is mod_rewrite and for IIS it is URL_rewrite plugin. Make a write rule that all formats with www at the start be turn into non www version. Consult your local server’s manuals on how to do it. Register the one without www
Hahahaah have you try by decline permission. You will see error with logout button. Write better script or stop writing.
If you have nothing constructive to say don’t say anything. This guy has written a good script and certainly gets you thinking. All programmers make mistakes if they didn’t we wouldn’t never see such emphasis on debugging.
If you have nothing constructive to say don’t say anything. This guy has written a good script and certainly gets you thinking. All programmers make mistakes if they didn’t we wouldn’t never see such emphasis on debugging.
If you have nothing constructive to say don’t say anything. This guy has written a good script and certainly gets you thinking. All programmers make mistakes if they didn’t we wouldn’t never see such emphasis on debugging.
If you have nothing constructive to say don’t say anything. This guy has written a good script and certainly gets you thinking. All programmers make mistakes if they didn’t we wouldn’t never see such emphasis on debugging.
Hello, Im getting an error
“Invalid redirect_uri: Given URL is not allowed by the Application configuration”, Im thinking that this method is already outdated. they facebook updated the graph api? Thanks
What URL you are sending?
I was able to get it working. but I can only get the name and ID no other information like email etc. I believe we need to change the /me? but I’m not sure what to change. Thanks