facebook->getUser() method returning 0 - php

I am having login using facebook functionality in my site. The issue is after getting successful authentication the $facebook->getUser() method returning 0, due to this it's not preceding towards the rest of code. To resolve this issue I modified my APP ID and Secret Key, also I created new APP but still its not working. Also did lot of stuff on google but didn't got any success.
Following is my code :
public function facebookregisterAction() {
require 'auth/src/facebook.php';
$facebook = new Facebook(array('appId' => 'xxxxxxxxxxxxxxx','secret' => 'xxxxxxxxxxxxxxxxxxxxxxx','cookie' => true));
$session = new Zend_Session_Namespace('user');
$user = $facebook->getUser();
if ($session->islogout != 1) {
if ($user) {
try {
$user_profile = $facebook->api('/me');
}catch(Exception $e){}
}
}
Thanks

As a general answer, I found it helpful to start with example.php in the facebook-php-sdk directory.
In my case my test application's URL was different than the site URL. The example.php file provided an error message that was useful enough to diagnose and correct the issue.
It's also a good example of actual usage.
With that said, there's a part that you seem to be missing. The user will have to visit your app's Facebook login URL before the API will be very useful (beyond fetching public information). To find this URL, try:
$url = $facebook->getLoginUrl();
You can give the user a link to click, or quietly redirect the user to this URL if you're requiring a login. A "Hello, World!"-type start would be something like:
if ($user) {
$url = $facebook->getLogoutUrl();
$message = "Click here to log out";
} else {
$url = $facebook->getLoginUrl();
$message = "Click here to log in";
}
print "<a href=$url>$message</a>";
But you'll quickly run into something that is covered by the example.php file: the "access token" (like a session ID) isn't cleared when the user logs out of Facebook. Your application will still see a valid user object, but any API call that hits Facebook will fail.

Related

user id not returning using facebook php sdk

$this->_facebookObj = new Facebook($config);
try
{
$this->_userId = $this->_facebookObj->getUser();
}
catch(Exception $e)
{
}
I've tried to run this sample code on my local machine with proper application id and secret key.
But response shows like I need an active access token. So i logged in to the Facebook,
then i get the user id successfully.
but whenever I logged out from Facebook I couldn't run the above sample code. I think its because of session.
How do we run above API when the user's logged in session not available?
I tried the following :
$this->_facebookObj->getAccessToken();
$this->_facebookObj->setAccessToken();
before making the getUser() API.
You should take a look at this answer as it explains how the authentication system work.
That said, here is how you can get the userId :
$facebook = new Facebook($config);
if (!$facebook->getUser())
{
// Cannot access the user account
}
// try to access the user on the fb api
try
{
$fbUser = $facebook->api('/me');
$id = $fbUser['id'];
}
catch (\Exception $e)
{
// Session expired, ask the user to log in again...
}

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.

Create facebook object each and every time?

I have a login page which will log a user into my webapp based on their facebook login details.
I then create a session to remember who they are.
What I want to know is, should I be creating and/or checking the facebook credential on every single page of my webapp, or should I simply use the session I create at the beginning to login?
For example, once they have logged in, I would like to allow them to post a message onto their own facebook wall from my app. Should I check the login credentials before they can post by recreating the facebook object, or should I simply use the stored login details already in my session and use that to post to their facebook wall?
UPDATE:
So basically, should I be using the following code as a template each and every time I want to do something facebook related, like post to their wall, login etc etc?
<?php
session_start();
# The facebook library
require_once("facebook.php");
# Create facebook object
$config = array();
$config['appId'] = 'appId goes here';
$config['secret'] = 'secret goes here';
$config['fileUpload'] = false; // optional
$facebook = new Facebook($config);
# Check if user has active facebook session
$user_id = $facebook->getUser();
if ($user_id) {
try {
// do something here
} catch (FacebookApiException $e) {
error_log($e);
$user_id = null;
exit;
}
} else {
$loginUrl = $facebook->getLoginUrl();
header("Location: ".$loginUrl);
}
?>
I’d check the user in every request, just in case you have brittle code that may allow a user to create sessions themselves.
I'd check the user on every request. If you want to make a post via the facebook api, you will need to have a valid facebook access_token. If you check on every page (combined with the js SDK) then the user will be signed back into your site again, rather than you getting an access token error and having to ask them to sign in again

Facebook PHP SDK - User not authenticated

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.

Categories