This question already has an answer here:
Codeigniter, Facebook javascript SDK, PHP SDK Redirect after facebook login doesn't getUser() until refresh
(1 answer)
Closed 5 years ago.
I am implementing Facebook login using the PHP SDK with Codeigniter. I get the Facebook login popup, hit login, but I am unable to retrieve the user's id - it always returns 0.
I have put the facebook.php and base_facebook.php files in my libraries file and included it as a library in Codeigniter following a tutorial here.
Can anyone tell me what they think is going on? I am using the following code -
View - Facebook login button
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({
appId : '<?php echo $this->config->item('facebook_app_id'); ?>',
status : true,
cookie : true,
xfbml : true,
oauth : true,
});
FB.Event.subscribe('auth.login', function() {
window.location='<?php echo base_url(); ?>auth_other/fb_signin/';
});
};
(function(d){
var js, id = 'facebook-jssdk'; if (d.getElementById(id)) {return;}
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "//connect.facebook.net/en_US/all.js";
d.getElementsByTagName('head')[0].appendChild(js);
}(document));
</script>
<div class="fb-login-button">Login with Facebook</div>
Controller - auth_other/fb_signin
function fb_signin()
{
$fb_user = null;
$fb_config = array(
'appId' => $this->config->item('facebook_app_id'),
'secret' => $this->config->item('facebook_app_secret')
);
$this->load->library('facebook',$fb_config);
$fb_user = $this->facebook->getUser();
echo $fb_user;
I was stuck up with similar issue, here is the solution that may help you.
$facebook = new Facebook(array(
'appId' => 'xxxx',
'secret' => 'xxxxx',
"redirect_uri" => "set the uri to point to the same page"
));
$user = $facebook->getUser();
if($user)
{
//your task
} else {
header('location:'. $facebook->getLoginUrl());
}
$user = $facebook->getUser();
if($user)
{
//your task
} else {
header('location:'. $facebook->getLoginUrl());
}
Came across a situation where getUser() was returning 0 when it really shouldn't be, the application was still sandboxed. Turns out the user hadn't accept the request to be developer of the application.
I've encountered a similar problem. I used an example project, and couldn't figure out why it keeps returning 0. tried nearly all related links here but none solved it.
The solution was to update Facebook's SDK files in the example project.
Simple and easily missed,
I had same issue, After long time of trying to figure out what the issue is,
I found that you need access token to get user ID.
To get access token form the signed_request, user must authorize (to get permissions) you app firstly.
I hope this will help
If App domain is real domain but site url is localhost, getUser function return 0
Related
I’m new to PHP and tying to set up a page as so users can login using Facebook PHP SDK and JavaScript SDK. I keep getting the fallowing error and I don’t seem to be able to find a solution.
I saw a similar post in here but I couldn’t give solution to the error.
Parse error: syntax error, unexpected T_STRING, expecting ',' or ';' in /homepages/9/d321009915/htdocs/kno_login/login.php on line 2
Here is my code:
<?php
echo '<div id='fb-root'></div>';
require_once("facebook.php");
$config = array();
$config['appId'] = 'some id';
$config['secret'] = 'something here';
$facebook = new Facebook($config);
?>
<script>
window.fbAsyncInit = function() {
FB.init({
appId : '293441190799565', // App ID
channelUrl : '//www.reyesmotion.com/kno_login/channel.html', // Channel File
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
// Here we subscribe to the auth.authResponseChange JavaScript event. This event is fired
// for any authentication related change, such as login, logout or session refresh. This means that
// whenever someone who was previously logged out tries to log in again, the correct case below
// will be handled.
FB.Event.subscribe('auth.authResponseChange', function(response) {
// Here we specify what we do with the response anytime this event occurs.
if (response.status === 'connected') {
// The response object is returned with a status field that lets the app know the current
// login status of the person. In this case, we're handling the situation where they
// have logged in to the app.
testAPI();
} else if (response.status === 'not_authorized') {
// In this case, the person is logged into Facebook, but not into the app, so we call
// FB.login() to prompt them to do so.
// In real-life usage, you wouldn't want to immediately prompt someone to login
// like this, for two reasons:
// (1) JavaScript created popup windows are blocked by most browsers unless they
// result from direct interaction from people using the app (such as a mouse click)
// (2) it is a bad experience to be continually prompted to login upon page load.
FB.login();
} else {
// In this case, the person is not logged into Facebook, so we call the login()
// function to prompt them to do so. Note that at this stage there is no indication
// of whether they are logged into the app. If they aren't then they'll see the Login
// dialog right after they log in to Facebook.
// The same caveats as above apply to the FB.login() call here.
FB.login();
}
});
};
// Load the SDK asynchronously
(function(d){
var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
if (d.getElementById(id)) {return;}
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "//connect.facebook.net/en_US/all.js";
ref.parentNode.insertBefore(js, ref);
}(document));
// Here we run a very simple test of the Graph API after login is successful.
// This testAPI() function is only called in those cases.
function testAPI() {
console.log('Welcome! Fetching your information.... ');
FB.api('/me', function(response) {
console.log('Good to see you, ' + response.name + '.');
});
}
</script>
<!--
Below we include the Login Button social plugin. This button uses the JavaScript SDK to
present a graphical Login button that triggers the FB.login() function when clicked.
Learn more about options for the login button plugin:
/docs/reference/plugins/login/ -->
<?php
echo '<fb:login-button show-faces="true" width="200" max-rows="1"></fb:login-button>';
?>
Just change the outer single quotes to double
echo "<div id='fb-root'></div>";
I'm trying to work with Facebook's default PHP website integration and authentication.
When a user logs in, I'm able to request permissions to get various information from the user.
This question is kind of old. Please take note of harkirat1892's comment.
"If someone using Facebook SDK v4.4 is stumbling across this question, the answer by Dhiraj won't >work in that case as there is a small change. You don't have to include redirect_uri in the array >passed to getLoginUrl.
As per v4.4, getLoginUrl should work like:
$loginUrl = $facebook->getLoginUrl(
array(
'scope' => 'email,user_checkins, user_birthday'
)
);
The various scopes can be found here: Facebook permissions."
It was really easy to figure out how to do it with the JavaScript one, but I'm confused where to specify the scope in the PHP example.
Basically, I just want to request for permission to access their email & location and maybe some other information.
Here is the code I'm working with:
(It's modified slightly, but it is almost an exact match to what they had.)
<?php
define('YOUR_APP_ID', '---------');
define('YOUR_APP_SECRET', '------------');
//Uses the PHP SDK. Download from https://github.com/facebook/php-sdk
require 'facebook.php';
$facebook = new Facebook(array(
'appId' => YOUR_APP_ID,
'secret' => YOUR_APP_SECRET,
));
$FBUID = $facebook->getUser();
?>
<?php if ($FBUID) {
$userInfo = $facebook->api('/' + $FBUID); ?>
<?php $FBName = $userInfo['name'];?>
<!--
Welcome <? // = $userInfo['name'] ?> -->
<?php } else { ?>
<div id="fb-root"></div>
<fb:login-button></fb:login-button>
<?php } ?>
<script>
window.fbAsyncInit = function() {
FB.init({
appId : '---------------',
status : true,
cookie : true,
xfbml : true,
oauth : true,
});
FB.Event.subscribe('auth.login', function(response) {
window.location.reload();
});
};
(function(d){
var js, id = 'facebook-jssdk'; if (d.getElementById(id)) {return;}
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "//connect.facebook.net/en_US/all.js";
d.getElementsByTagName('head')[0].appendChild(js);
}(document));
</script>
This is how you typically specify scope in PHP (check the documentation):
$facebook = new Facebook(array(
'appId' => AppInfo::appID(),
'secret' => AppInfo::appSecret(),
));
$loginUrl = $facebook->getLoginUrl(
array(
'scope' => 'read_stream,publish_stream,publish_actions,manage_pages,email,user_checkins',
'redirect_uri' => $redirectURI
)
);
I hope this helps.
The answer above is great but, Facebook just loves to change things up. The best answer checked off on this forum is for a version of Facebook SDK, which is out of date. Similar to the example above, here is how you would request permissions or a scope for version 5.0.
session_start();
$F = new \Facebook\Facebook([
'app_id' => 'app-id',
'app_secret' => 'app-secret',
'default_graph_version' => 'v2.8'
]);
$helper = $F->getRedirectLoginHelper();
$callBackUrl = "http://website.com/callBack.php";
$scope = array("email","user_likes");
$loginUrl = $helper->getLoginUrl($url,$scope);
Also, I noticed the answer above is a request for "user_checkins" which I believe is deprecated. The most current reference list of permissions is here.
If someone using Facebook SDK v4.4 is stumbling across this question, the answer by Dhiraj won't work in that case as there is a small change. You don't have to include redirect_uri in the array passed to getLoginUrl.
As per v4.4, getLoginUrl should work like:
$loginUrl = $facebook->getLoginUrl(
array(
'scope' => 'email, user_checkins, user_birthday'
)
);
The various scopes can be found here: Facebook permissions.
I am getting same issue and got below solution. Might it help you :
Open your app in facebook developer console and then select app reviews section on left side.
Submit Items for Approval. Some permissions need to take approval from facebook before using.
:)
I am integration Facebook connect in my website using php SDK.. Everything is working fine except that I want that instead of redirecting to facebook for authentication, I want to open OAuth Dialog.. Currently Im using following url for authentication,.. It redirects to facebook but doesn't open OAuth Dailog..
https://www.facebook.com/dialog/oauth?client_id=XXXXXXXXXXX&redirect_uri=http%3A%2F%2Fwww.setsail2nz.com.au%2Fmicrosite%2Ffbalbums.php%3Fpid%3D1&state=ad89eddd7f71e7337785f604710c97e8&scope=user_photos%2Cpublish_stream%2Cmanage_friendlists%2Cemail&display=popup
Any ideas?
EDIT:
I know how to do it with Facebook JS SDK.. But is there a way to do it with php?
Edit 2: Okay now im using JS SDK but still its not opening the dialog.. Here is my code
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({
appId : 'XXXXXXXXXX', // App ID
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true, // parse XFBML
oauth : true // enables OAuth 2.0
});
};
// Load the SDK Asynchronously
(function(d){
var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
if (d.getElementById(id)) {return;}
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "//connect.facebook.net/en_US/all.js";
ref.parentNode.insertBefore(js, ref);
}(document));
function fblogin()
{
FB.login(function(response)
{
alert(response);
},{perms: "user_photos,publish_stream,manage_friendlists,email"});
}
</script>
Use Javascript SDK
https://developers.facebook.com/docs/reference/javascript/
And FB.login, passing your required permissions
To answer your question about detecting the dialog response with PHP SDK:
The problem is that getloginURL only takes one URL parameter that it uses on success or error. I needed to detect if the user clicked OK or Cancel on the permissions dialog, so I could either redirect to a pre-permissions dialog page, or show the correct logged-in content.
All I did was check if 'error_reason' existed in the url parameters, and if the error was 'user_denied', and took appropriate action. There might be a better way, but this worked for me.
<?php
//Facebook Authentication
$user = $facebook->getUser();
//Get Login URL
$loginUrl = $facebook->getLoginUrl();
//User is logged in
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 is not logged in
if (!$user) {
//Check if error_reason was generated and if the user denied login
if (isset($_REQUEST['error_reason']) && ($_REQUEST['error_reason']=='user_denied')) {
//user cancelled permissions dialog thus not logged in to app, redirect elsewhere
echo "<script type='text/javascript'>top.location.href = 'YOUR REDIRECT URL';</script>";
exit;
} else {
//user not logged in so initiate permissions dialog
echo "<script type='text/javascript'>top.location.href = '$loginUrl';</script>";
exit;
}
}
//get user basic description
$userInfo = $facebook->api("/$user");
?>
How do I make a logout using Facebook's api log me out of my app (a website), but keep me logged into facebook.com?
This logs me in alright:
window.fbAsyncInit = function()
{
FB.init({
appId : '<?= APP_ID ?>',
status : true,
cookie : true,
xfbml : true,
oauth : true,
});
FB.Event.subscribe('auth.login', function(response)
{alert(response);
window.location = 'http://reviewsie.com/accounts/facebook';
});
};
(function(d)
{
var js, id = 'facebook-jssdk'; if (d.getElementById(id)) {return;}
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "//connect.facebook.net/en_US/all.js";
d.getElementsByTagName('head')[0].appendChild(js);
}(document));
But then I click logout on my site which I kill my session to my app. Then when you click on the fb:login-button again, it just opens and closes and doesn't do anything because I'm still connected to facebook. I want it to redirect.
But if when I logout I also use Facebook::logoutUrl it logs me out of my app AND facebook which is not what I want.
A bit late but might help someone. You can revoke app permissions which effectively logs them out of your app. Here's the code:
FB.api('/me/permissions', 'delete', function(response) {
console.log(response.status); // true for successful logout.
});
This works for me:
window.fbAsyncInit = function() {
FB.getLoginStatus(function(response) {
FB.api("/me/permissions", "delete", function(response){
});
});
}
Are you sure you want to only logout of your app, and not fb too, if you logged in using fb? What kind of app could want to do something like that? And why? What's the benefit of doing so?
But if you really want to (hack), in index.php:
<?php
require 'init.php'; // general init
require 'init_fb.php'; // sets $fb_id if logged in to fb
if (isset($fb_id) and !isset($_SESSION['do_not_auto_login'])) {
echo "<a href='/logout'>Logout</button>";
include 'app.php';
return;
}
if (isset($_SESSION['do_not_auto_login'])
echo "<a href='/re_login'>FB Login</button>";
else include 'html_and_js_fb_login_code_and_button.php';
include 'startpage.php';
?>
and in logout.php:
$_SESSION['do_not_auto_login'] = true;
// destroy-code
and in re_login.php:
unset($_SESSION['do_not_auto_login']);
header("location: /"); // re-direct back to index.php
Not perfect, but works somewhat good. Hope you get the hack!
But still, why?? If you don't think your user would like to come back, ask "How to remove my fb-app from user?" or something instead or try #DMCS's answer.. Why?
You need to use destroySession for Facebook to do
www.example.com?act=logout
<?php
php sdk blah blah
if($_GET['act'] =='logout'){
$facebook->destroySession();
}
$params = array(
'scope' => 'read_stream, friends_likes',
'redirect_uri' => 'https://www.myapp.com/post_login_page'
);
$loginUrl = $facebook->getLoginUrl($params);
?>
Maybe you need to set param to make it redirect.
When the user is logged into your app, send an HTTP DELETE call to /me/permissions using their current access token. This will log them out of your app requiring them to re-authenticate if they want to play some more. Also be sure to destroy the php session using normal php session clearing code.
I am trying to migrate to the new Facebook API for websites, and just can't get it to work smoothly. I would like to use the Javascript and PHP SDKs together, but am having problems. I can authenticate, but the page doesn't refresh automatically.
I have searched throughout SO and the Facebook documentation, but still can't get this to work correctly. I have read through http://developers.facebook.com/blog/post/534/, dowloaded the latest PHP SDK (3.1.1), and basically copied the example on the aforementioned post from facebook. I have made what I think are the correct settings in my app 'Migration' settings, but this could be where the problem lies. I can't post an image, so here are the setting:
Remove Deprecated API's: Enabled
Forces use of login secret: Enabled
Encrypted Access token: Enabled
Enhanced Auth Dialog: Enabled
(Everything else is disabled)
Here is the code:
<?php
require 'php-sdk/src/facebook.php';
$facebook = new Facebook(array(
'appId' => 'YOUR_APP_ID',
'secret' => 'YOUR_APP_SECRET',
));
// See if there is a user from a cookie
$user = $facebook->getUser();
if ($user) {
try {
// Proceed knowing you have a logged in user who's authenticated.
$user_profile = $facebook->api('/me');
} catch (FacebookApiException $e) {
echo '<pre>'.htmlspecialchars(print_r($e, true)).'</pre>';
$user = null;
}
}
?>
<!DOCTYPE html>
<html xmlns:fb="http://www.facebook.com/2008/fbml">
<body>
<?php if ($user_profile) { ?>
Your user profile is
<pre>
<?php print htmlspecialchars(print_r($user_profile, true)) ?>
</pre>
<?php } else { ?>
<fb:login-button></fb:login-button>
<?php } ?>
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({
appId: '<?php echo $facebook->getAppID() ?>',
cookie: true,
xfbml: true,
oauth: true
});
FB.Event.subscribe('auth.login', function(response) {
window.location.reload();
});
FB.Event.subscribe('auth.logout', function(response) {
window.location.reload();
});
};
(function() {
var e = document.createElement('script'); e.async = true;
e.src = document.location.protocol +
'//connect.facebook.net/en_US/all.js';
document.getElementById('fb-root').appendChild(e);
}());
</script>
</body>
</html>
I was going to write this as a comment but it got a bit long... :)
A couple of pointers using the PHP SDK:
$facebook->getUser();
This will work regardless of authentication. getUser() pulls publicly available data that does not require an access token, HOWEVER if you do have an access token and the user has provided email permissions for example, this method will also contain their email address.
A better test for an authenticated user:
$code = $_REQUEST['code'] ? true : false;
if (!$code) {
echo ("<script>window.top.location=\"...\"</script>");
}
will check if a user has authorised your app.
$access = $facebook->getAccessToken();
Make sure that you always request the Access Token (priority!) You will only ever recieve a signed request when you have been redirected from a facebook dialogue to your app. (i.e.) oAUTH dialogue. This method of the SDK will also save your Access Token to a session variable. You can call the getAccessToken() method on any subsequent app page where a PHP session is active EVEN WHEN no signed request has been issued.
Now that you have your valid access token for the logged in user, you can proceed with:
$user = $facebook->api('/me');
or, simpler still:
$user = $facebook->getUser();
I tend to reserve API calls for more complex requests such as posting to a users feed / friends feed.
So to recap:
-> check for $code
-> get signed request on first page after oAuth dialogue.
-> If browser cookies are disabled (likely in ie) don't forget to pass your session to the next page with the SID constant. If you don't, you will loose your stored access token (not good!).