Facebook PHP SDK - User not authenticated - php

I am using Facebook PHP SDK to authenticate the user. After generating the LoginUrl using the PHP SDK, the user clicking on that LoginUrl gets redirected to the Facebook page asking for permission. After clicking on the Go to App link, the user gets redirected back to my website http://www.mydomain.com/login/facebook_connect.
Problem: After being 'authenticated' by Facebook, the PHP script at http://www.mydomain.com/login/facebook_connect is unable to determine that the user has logged in via Facebook. At this point, $user = $facebook->getUser(); is 0.
Did I do something wrong? Thanks!
PHP Code for page that generates LoginUrl
require 'libs/fb-php-sdk/facebook.php';
// Create our Application instance
$facebook = new Facebook(array(
'appId' => '123',
'secret' => '123'
));
// Get User ID
$user = $facebook->getUser();
// Get Login URL
$loginUrl = $facebook->getLoginUrl(array(
"scope" => "email,user_education_history,user_work_history",
"redirect_uri" => "http://www.mydomain.com/login/facebook_connect/"
));
$data['fb_login_url'] = $loginUrl;
$this->load->view('splash', $data);
PHP Code for page user is redirected to after Facebook authentication
*http://www.mydomain.com/login/facebook_connect/*
require 'libs/fb-php-sdk/facebook.php';
$facebook = new Facebook(array(
'appId' => '123',
'secret' => '123',
));
// See if there is a user from a cookie
$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) {
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;
}
}
print_r($user_profile);
echo $user;

All seems correct.
Questions:
1.- I supposed that http://www.mydomain.com/ contains all your scripts, right?
2.- Are you using codeigniter? Or a codeigniter-based CMS? In that case maybe you have a session problem (very common in CI). Check it and we continue...
EDIT 2: In case of being a cookie related problem. Here is an image showing as you can use firebug with a cookie module to easily track your cookies:
So you can check how facebook cookies are being generated.
EDIT 3: Ok. So you are using CI and your FB cookies are being deleted. Maybe is a session problem. Here is a related answer where I explain how to use a session CI library replacement that generally solve all these kind of painful issues. Believe me, give it a try!
a.- Here it is: Codeigniter's Native session (there is a download link at the bottom)
b.- BUT, due that it is an old library you MUST made some hacks. You can check those simple hacks in the library's forum
c.- Just drop this file in codeigniter's library directory.

$facebook->getUser() uses a cookie to get the user. If you use CodeIgniter, or another library that "eats" cookies that PHP assigns automatically, you need to create a proxy page outside CI, that would pick up the cookie the redirect back into CI.
In other words, take to code you currently have in
http://www.mydomain.com/login/facebook_connect/
and create a copy in a regular PHP file:
http://www.mydomain.com/facebook_pickup.php
do not echo anything from the script (remove print_r), just redirect to
http://www.mydomain.com/login/facebook_connect/
and it would magically start working.

Related

facebook login bug using fb php sdk

My problem is the following.
I have a website
http://de.gamercharts.com/
You can connect with facebook(if you don't have an account,an account will be created).
After this ,if you logout from the site ,you are logged out from facebook too.
Everything is ok so far.
The problem is that if I am logged out of the site (let's call the site GC) and logged out of facebook ,when I click "connect with facebook" on the site,I get logged in on the site,instead of being prompted to the facebook login screen.
When I print the user ,I see that even though I am logged out of facebook,I still have the user id.
Why does this happen,and how can I fix it ?
Thanx a lot to anyone who takes the time to answer.
For the record I am using Zend ,although I don't think it's relevant.
I did not implement the facebook login myself,I am continuing the work of someone else.
The problem is caused due to existence of Facebook Session Variables in your domain/site, even after logging out from facebook and your site. When someone logs out from your site, one should take care to destroy all the sessions[even facebook sessions]. For destroying facebook sessions in your domain/site, you can make use of the function destroySession(); [provided in the facebook php sdk] in your logout script.
$config = array();
$config['appId'] = 'YOUR_APP_ID';
$config['secret'] = 'YOUR_APP_SECRET';
$facebook = new Facebook($config);
$logout = $this->facebook->getLogoutUrl(array('next'=>'url to be redirected after logout'));
$facebook->destroySession(); // To destroy facebook Sessions
$session_destroy(); //To destroy sessions of your site
header("Location:$logout");
P.S Don't forget to include or call session_start() in the script
If you use facebook sdk, then you need use exception try-catch for checking if user is still logged in:
1$facebook = new Facebook(array(
2 'appId' => you id,
3 'secret' => you secret,
4));
5
6// See if there is a user from a cookie
7$user = $facebook->getUser();
8
9if ($user) {
10 try {
11 // Proceed knowing you have a logged in user who's authenticated.
12 $user_profile = $facebook->api('/me');
13 } catch (FacebookApiException $e) {
14 error_log($e);
15 $user = null;
16 }
17}
And after that you can get correct user id and other information from Facebook
Every time you need to request me-page. And if this page throw an error, then delete facebook user's data. User's id, and other facebook data stored in the cookies; when you logged out in the Facebook site, cookies for you site continue to be kept; your php-code will read this cookies:
1$user = $facebook->getUser();
and return user id.
With this code:
1$user_profile = $facebook->api('/me');
you check if this cookies is actuall, and if it isn't, you change it:
1$user = null;
All the matter in cookies

facebooks sharedSession returning "The page isn't redirecting properly"

I'm trying to activate cookies via the facebook login so it doesnt always depend on the session being there but whenever I set sharedSession to true I get a "The page isn't redirecting properly" error page.. Is this the way I'm suppose to make it so the facebook login uses cookies? I'm using the newest code on github for the facebook SDK (downloaded a freshy today) -> https://github.com/facebook/facebook-php-sdk
I'm not using the javascript SDK. and all of the coding below is fired before any headers are sent out. If I take the sharedSession out, it logs me in correctly, but it doesnt store a cookie with the info needed.
Heres the coding I'm using
$facebook = new Facebook(array(
'appId' => $Sets['facebook']['appId'],
'secret' => $Sets['facebook']['appSecret'],
'sharedSession' => true,
// 'trustForwarded' => true
));
$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) {
$user = null;
}
}
// the user is logged into facebook
if($user){
// I register them on my website..
// and then send them to the index page
header('Location: /index.php');
} else {
// they are not registered through facebook
if(isset($_GET['error'])){
// this happens when an error is found
die($_GET['error'].' error');
// header("Location: /login/?error=".urlencode($_GET['error']));
exit;
} else {
// send to facebook to log them in.
$loginUrl = $facebook->getLoginUrl($Sets['facebook']['scope_array']);
// die('sending to '.$loginUrl);
header("Location: ".$loginUrl);
exit;
}
}
You can see I put the die() function before any redirection there, this was for debugging on my end to see if I can figure out where it was failing, but it seems to happen after the user is returned to the website.. I also tried the trustForward => true, but that didnt fix it..
all I'm after is to be able to have the user logged in for a longer period of time, without having to login through facebook everytime they visit the website.
Whats happening is the user is stuck in a loop trying to log into facebook being redirected between facebook and my website because the user is never verified. Again, this ONLY happens when I set 'sharedSession' => true
I'm trying to get the facebook sdk to store a cookie from my website onto the persons computer that tries to login but no cookie is being set.
I get confused by your question. what do you want to achieve:
1) If you want to set store your facebook user_id to cookie, you don't have to do anything. when the oauth process is completed facebook redirect to your "redirect_uri" url, the cookie is set by facebook to a cookie value: fbsr_xxxx (xxxx is your appId)
2) If you want to keep user logged in longer time, you need to set your own session value to determine if the user is logged in or not. in other word, after the facebook oauth flow, your user login status has nothing to do with your facebook session.
BTW: $Users->loginWithOauth, this function has no definition, what's this function for?
the reason is the required permission not granted so eventually it goes to facebook search for the token and comes back.
check for the permission you need.

$user = $facebook->getUser() returning 0 everytime. Am using the latest SDK

Am using below code to check whether the user is logged in or not to Facebook.
<?php
// Awesome FB APP
// Name: MyAPP
require_once 'facebook.php';// this line calls our facebook.php file that is the
//core of PHP facebook API
// Create our Application instance.
$facebook = new Facebook(array(
'appId' => '250941738370233',
'secret' => 'xxx',
'cookie' => true,
)); // all we are doing is creating an array for facebook to use with our
$user = $facebook->getUser();
echo $user;
//app id and app secret in and setting the cookie to true
if($user){
try {
$user_profile = $facebook->api('/me');
} catch (FacebookApiException $e) {
error_log($e);
$user=null;
} // this code is saying if the session to the app is created use
}
//the $me as a selector for the information or die
?>
But the $user is responding 0 everytime. Am badly stuck at this point. Can someone help me out here.
Am using below code to check whether the user is logged in or not to Facebook.
I’m suspecting that’s your problem right there.
You can not check if any user visiting your app is logged into Facebook – you will only get information about a user, if they have connected to your app before. And since I see nothing like it in your code, I assume you did not trigger that in any way before.
So please, start reading docs here: https://developers.facebook.com/docs/technical-guides/login/
Getting a 0 is to be expected. You should, on getting that, be redirecting the user to a login url. If you do that, the user will get one of those App authorisation screens you have seen, after which they will be redirected to whatevef url you have specified.
Check out the links provided, but also take a peek at http://www.facebookanswers.co.uk/?p=229 as I provide some examples there.
The example in my link really needs updating but if you look you will see that it checks to see if getuser returns false, and if so jumps to a login page.

Connect to a facebook app for longer than a session

I've been searching and trying around for a couple of hours, but I can't figure it out.
I use a facebook app to get some information of the user, therefor the user needs to connect to the app. The first time the user connects, he needs to give permission to the app on facebook. When the user comes back another day, he needs to click connect again, but the permission is already set.
I want the user to be connected longer than the session, so he doesn't need to click connect everytime he visits the site (in a new session). I've read a lot about offline_access etc but this is deprecated and probably not what I need at last. I've also read some solutions from 2 years ago, but they don't work anymore.
An example to summarize:
Assume the user visits my website and I know nothing about him. He gave permission to my app a few days ago. I want him to see Hello and the logoutlink without doing anything. I'm starting to wonder if this is even possible?
// Create our Application instance.
$facebook = new Facebook(
array(
'appId' => xxxxxxxxxx,
'secret' => xxxxxxxxxx,
)
);
// Get User ID
$fbuser = $facebook->getUser();
if($fbuser) {
$logoutUrl = $facebook->getLogoutUrl();
print 'Hello' . $logoutUrl;
} else {
$loginUrl = $facebook->getLoginUrl();
}
Thank you in advance!
Regards
I don't think that php is the way to go with this one...
You should use the facebook javascript sdk (https://developers.facebook.com/docs/reference/javascript/) with which you can log the user in..
If the user is already logged in to facebook and has a session (and of course has already authorized your application before) then you are all set, otherwise the user will have to login to facebook or authorize you application.
use the FB.getLoginStatus to check if the user is logged in, if he is not then present him with a button that will call the FB.login method
Yes you should only use facebook to get certain data then you should store all that data with the unique fb_user_id in your own database and create your own session for the user!
So during facebook signup social plugin you create a user in your own database, then during each login you actually create you own session and if you make it secure you can rely on your own session, if you use any facebook API stuff and your session is closed it will handle it on the facebook server, it might ask user to log in if they are logged out of facebook, but most people don't even logout so it just recreates the session!
so something like:
// Create our Application instance.
$facebook = new Facebook(
array(
'appId' => xxxxxxxxxx,
'secret' => xxxxxxxxxx,
)
);
inlcude "my_session_stuff.inc";
// Get User ID
if(!$user->user_exists){
$fbuser = $facebook->getUser();
}else{
$fbuser = $user;
}
if($fbuser) {
$logoutUrl = $facebook->getLogoutUrl();
$expires = (60*60*24*365);//expire in a year
$user = $myownSession->log_user_out($logoutUrl);
} else {
$loginUrl = $facebook->getLoginUrl();
$user = $myownSession->log_user_in($getLoginUrl,$expires);
}

Facebook Application with PHP running losing session

Iam trying to build an Facebook Application based on PHP. The Application is running under php on my own Webhost inside an Canvas as iFrame.
I have included the newest Client Library for PHP from Facebook: facebook-php-sdk-94fcb13
To Authorize the user inside my application iam trying to use Facebook Connect, like the example shipped with the Client. Everything works fine the 1st Login, but when i hit the F5 Key to reload the page, the session is lost and i have to login again. When i call my application outside of the Facebook Canvas everything is fine.
Iam not sure, but i think my Browser (Chrome/FireFox - Ubuntu) is not allowing to store an cookie inside an iFrame.
Does someone knows an solution for this Problem? Here are some Parts of the Sourcecode:
$facebook = new Facebook(array(
'appId' => 'x',
'secret' => 'x',
'cookie' => 'true',
));
$session = $facebook->getSession();
$facebook->setSession($session);
$me = null;
// Session based API call.
if ($session) {
try {
$uid = $facebook->getUser();
$me = $facebook->api('/me');
} catch (FacebookApiException $e) {
error_log($e);
}
}
// login or logout url will be needed depending on current user state.
if ($me) {
$logoutUrl = $facebook->getLogoutUrl();
} else {
$loginUrl = $facebook->getLoginUrl();
}
Solved :-)
I have missed to setup the basedomain in configuration.
On the "Conntect" Tab you have to set the Basedomain to your host.
Example: Application is running under http://myapp.com/facebook/html than set the basedomain
to myapp.com
Now the cookie is stored correctly.
php passes the session id via a cookie value , if its not able to send it , sends via get parameter like *.php?phpsessid......
It will get lost if u use header() redirection , solution append .SID in url,
like
header("blah blah".SID);
Hope it helps you..

Categories