Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP SDK 3.1.1 getUser() sometimes return 0

This is driving me crazy >=(

$facebook->getUser() works well sometimes, but sometimes returns 0

Here is my code: require 'fbapi/facebook.php';
$facebook = new Facebook(array(
'appId' => 'xxx',
'secret' => 'xxxxx',
));
$user = $facebook->getUser();

the appId and secret are the correct ones.

Which could be the reason that getUser sometimes it returns 0???

like image 712
Phoxer Avatar asked Aug 29 '11 06:08

Phoxer


3 Answers

It's more than likely something on Facebook's end (devs have gone through this before a while back). If $user returns null or 0, simply reroute them to the login url (which you should have). The liklihood of it returning 0 again is minimal (unless there's a bug on their end or there's more to your code than what you've posted).

like image 123
Phillip Avatar answered Oct 25 '22 00:10

Phillip


I ran into similar problem. $facebook->getUser() was returning 0 and sometimes it returned valid user id when user wasn't actually logged in, resulting in Fatal Oauth error when I tried to make graph api calls. I finally solved this problem. I don't know if it is the right way but it works. Here is the code :

<?php
include 'includes/php/facebook.php';
$app_id = "APP_ID";
$app_secret = "SECRET_KEY";
$facebook = new Facebook(array(
    'appId' => $app_id,
    'secret' => $app_secret,
    'cookie' => true
));

$user = $facebook->getUser();

if ($user <> '0' && $user <> '') { /*if valid user id i.e. neither 0 nor blank nor null*/
try {
// Proceed knowing you have a logged in user who's authenticated.
$user_profile = $facebook->api('/me');
} catch (FacebookApiException $e) { /*sometimes it shows user id even if user in not logged in and it results in Oauth exception. In this case we will set it back to 0.*/
error_log($e);
$user = '0';
}
}
if ($user <> '0' && $user <> '') { /*So now we will have a valid user id with a valid oauth access token and so the code will work fine.*/
echo "UserId : " . $user;

$params = array( 'next' => 'http://www.quickbite.co.in' );
echo "<p><a href='". $facebook->getLogoutUrl($params) . "'>Logout</a>";

$user_profile = $facebook->api('/me');
echo "<p>Name : " . $user_profile['name'];
echo "<p>";
print_r($user_profile);

} else {/*If user id isn't present just redirect it to login url*/
header("Location:{$facebook->getLoginUrl(array('req_perms' => 'email,offline_access'))}");
}

?>
like image 39
anujkk Avatar answered Oct 25 '22 01:10

anujkk


You just input php header to

header('P3P: CP="NOI ADM DEV COM NAV OUR STP"');
like image 20
Gutonteen Avatar answered Oct 25 '22 01:10

Gutonteen