Facebook PHP SDK fails on first page load - php

The FIRST time my index.php loads I get a value of 0 when calling:
$facebook->getUser();//returning 0 instead of id on first page load
The call works fine on any subsequent page load.
This is my code:
$facebook = new Facebook(array(
'appId' => $FB_APP_ID,
'secret' => $FB_APP_SECRET
));
$user_id = $facebook->getUser();//Returns 0 on first load.
Has anyone else experienced this? Maybe I should automatically reload the page if $facebook->getUser(); does not return a valid user?

May be it is not authenticating it for very first time, You can do some thing like this:
<?php
$facebook = new Facebook(array(
'appId' => xxx,
'secret' => xxx
));
$user_id = $facebook->getUser();
if($user_id) {
// We have a user ID, so probably a logged in user.
// If not, we'll get an exception, which we handle below.
try {
$me = $facebook->api('/me','GET');
echo "Name: " . $me['name'];
} catch(FacebookApiException $e) {
// If the user is logged out, you can have a
// user ID even though the access token is invalid.
// In this case, we'll get an exception, so we'll redirect and
// just ask the user to login again here.
$login_url = $facebook->getLoginUrl();
echo("<script>top.location.href = '" . $loginUrl . "';</script>");
}
} else {
// No user, redirect for the user to login
$login_url = $facebook->getLoginUrl();
echo("<script>top.location.href = '" . $loginUrl . "';</script>");
}
?>
EDIT:
If error persists, try with this edit, just change your this line:
$me = $facebook->api('/me','GET');
to this:
$me= $facebook->api('/'.$user_id, 'GET');
Hope this will solve your problem.

Related

Facebook redirect url to index.php

index.php
<?php
//facebook application
$fbconfig['appid'] = "32##########";
$fbconfig['secret'] = "ca2dc#############";
$fbconfig['baseurl'] = "http://localhost/sbs/fblogin/index.php";
//
if (isset($_GET['request_ids'])) {
//user comes from invitation
//track them if you need
}
//facebook user uid
try {
include_once "src/facebook.php";
}
catch (Exception $o) {
error_log($o);
}
// Create our Application instance.
$facebook = new Facebook(array(
'appId' => $fbconfig['appid'],
'secret' => $fbconfig['secret'],
'baseurl' => $fbconfig['baseurl'],
'cookie' => true
));
//Facebook Authentication part
$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.
$loginUrl = $facebook->getLoginUrl(array(
'scope' => 'email,offline_access,publish_stream,user_birthday,user_location,user_work_history,user_about_me,user_hometown,user_photos ,user_work_history'
));
$logoutUrl = $facebook->getLogoutUrl();
if ($user) {
try {
// Proceed knowing you have a logged in user who's authenticated.
$user_profile = $facebook->api('/me');
}
catch (FacebookApiException $e) {
//you should use error_log($e); instead of printing the info on browser
// d is a debug function defined at the end of this file
$user = null;
}
}
//if user is logged in and session is valid.
if ($user) {
//get user basic description
$userInfo = $facebook->api("/$user?fields=picture,name,email,gender,birthday");
//$pic = $facebook->api("/$user/pictures");
$profile = json_encode($userInfo);
$res = json_decode($profile, true);
$_SESSION['name'] = $res['name'];
$_SESSION['email'] = $res['email'];
$_SESSION['id'] = $res['id'];
$_SESSION['gender'] = $res['gender'];
$_SESSION['birthday'] = $res['birthday'];
$_SESSION['img'] = $res['picture']['data']['url'];
$_SESSION['auth_type'] = "facebook";
if (isset($_COOKIE['registration']) && $_COOKIE['registration'] == true) {
header("location:../sbs/registration.php");
} else {
header("location:../sbs/sbs_login.php");
}
}
?>
For the 1st time I am working on the Facebook app. I have made app on the Facebook developer. It's working properly but it is not redirecting me in the index.php. I want to redirect it in this page only so all the values are stored in the session and I am checking it if the cookies is made then this value is going to registration.php and if not then its going to sbs_login.php. Please can anybody tell where to give the redirect url?
$loginUrl = $facebook->getLoginUrl(array(
'baseurl' => $fbconfig['baseurl'],
'scope' => 'email,offline_access,publish_stream,user_birthday,user_location,user_work_history,user_about_me,user_hometown,user_photos ,user_work_history'
));
I find the solution of my problem . so this is the solution
$loginUrl = $facebook->getLoginUrl(array(
'baseurl' => $fbconfig['baseurl'],
'scope' => 'email,offline_access,publish_stream,user_birthday,user_location,user_work_history,user_about_me,user_hometown,user_photos ,user_work_history'

Fceabook PHP SDK valid access token

I have search over and over again and I can't seem to find an answer. What am I doing wrong?
My error is FacebookApiException [ 0 ]: An active access token must be used to query information about the current user.
EDIT Just to add. This worked once or twice, but never in succession.
require_once('media/fb/facebook.php');
$app_id = '123456';
$app_secret = '123456';
$my_url = 'mysiteurl';
$config = array(
'appId' => $app_id,
'secret' => $app_secret,
'fileUload' => 'false');
$facebook = new Facebook($config);
$user = $facebook->getUser();
if($user) {
try {
$user_profile = $facebook->api('/me','GET');
} catch(FacebookApiException $e) {
error_log($e->getType());
error_log($e->getMessage());
}
} else {
$login_url = $facebook->getLoginUrl(array('redirect_uri' => $my_url));
header("Location:" . $login_url);
$user_profile = $facebook->api('/me','GET');
}
Your help is greatly appreciated.
Does your error come from this line: $user_profile = $facebook->api('/me','GET'); at the bottom?
The header function will re-direct the user to Facebook login page which will cause the browser to refresh. You won't get the user's access token immediately after that. You need to wait until the user is redirected back to your website to get the access token. You need to set $my_url to point to the same page of the codes you wrote here.

Facebook serverside login problems

So as the title sugests I am using Facebook php sdk to authorize the user on my site, the problem I am having is that after a few minutes of beeing logged in and I refresh the page the $user = $facebook->getUser(); is gone and the page thinks I am logged out but if I refresh again it's authorized again.
index.php
<?php
session_start();
include_once "facebook/fbaccess.php";
?>
fbaccess.php
<?php
//Application Configurations
$app_id = "xxxxxxxxxxxxx";
$app_secret = "XXXXXXXXXXXXXXXXXXXXX";
$site_url = "http://xxxxxxxxx";
try{
include_once "facebook.php";
}catch(Exception $e){
error_log($e);
}
// Create our application instance
$facebook = new Facebook(array(
'appId' => $app_id,
'secret' => $app_secret,
'cookie' => true
));
// Get User ID
$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.
$facebook->setExtendedAccessToken();
$access_token = $facebook->getAccessToken();
if($user){
//==================== Single query method ======================================
try{
// Proceed knowing you have a logged in user who's authenticated.
$user_profile = $facebook->api('/me');
$_SESSION['fid'] = $user_profile['id'];
}catch(FacebookApiException $e){
error_log($e);
$user = NULL;
}
//==================== Single query method ends =================================
}
if($user){
// Get logout URL
$logoutUrl = $facebook->getLogoutUrl();
}else{
// Get login URL
$loginUrl = $facebook->getLoginUrl(array(
'scope' => 'publish_stream', 'offline_access',
'redirect_uri' => $site_url,
));
}
?>
index.php
<div id="mainMenu">
<?php if ($user) {echo '<h5>Logout</h5>'; }else{ echo '<h5>Login</h5>';} ?>
</div>
I am using this tutorial for the login process: http://25labs.com/tutorial-integrate-facebook-connect-to-your-website-using-php-sdk-v-3-x-x-which-uses-graph-api/
Check your session lifetime settings and cookies. Does same behavior exist when you continiously browsing at your website or after some inactivity time only?

No Longer asks user to accept application for new users?

I used to have this code which sent the user to the normal app acceptance page once they went to my application page on facebook:
<?php
$auth_url = "http://www.facebook.com/dialog/oauth?client_id="
. $app_id . "&redirect_uri=" . urlencode($canvas_page)."&scope=email,user_photos,friends_photos";
$signed_request = $_REQUEST["signed_request"];
list($encoded_sig, $payload) = explode('.', $signed_request, 2);
$data = json_decode(base64_decode(strtr($payload, '-_', '+/')), true);
if (empty($data["user_id"])) {
echo("<script> top.location.href='" . $auth_url . "'</script>");
} else {
echo ("Welcome User: " . $data["user_id"]);
}
?>
With the new SDK I replaced all that with what is below:
<?php
require_once('src/facebook.php');
// Create our application instance
// (replace this with your appId and secret).
$facebook = new Facebook(array(
'appId' => $app_id,
'secret' => $app_secret,
));
// Get User ID
$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;
}
}
// Login or logout url will be needed depending on current user state.
if ($user) {
$logoutUrl = $facebook->getLogoutUrl();
} else {
$loginUrl = $facebook->getLoginUrl(array('scope'=>'email,user_photos,friends_photos'));
}
?>
My question is do I still need the top code for the correct page to come up which asks the user if they want grant access to my app? With just the bottom code this no longer happens?Iis there a newer way to do it with the new SDK?
Thanks!
Let's fix the code first:
<?php
require_once('src/facebook.php');
// Create our application instance
// (replace this with your appId and secret).
$facebook = new Facebook(array(
'appId' => $app_id,
'secret' => $app_secret,
));
$canvas_page = "YOUR_URL_HERE";
// Get User ID
$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');
echo '<pre>'.htmlspecialchars(print_r($user_profile, true)).'</pre>';
} catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
} else {
echo "<script>top.location.href='" . $facebook->getLoginUrl(array('scope'=>'email,user_photos,friends_photos', 'redirect_uri'=>$canvas_page)) . "';</script>";
}
?>
Notes:
you need to make sure you are linking to the SDK correctly
using $facebook->getUser() will check the signed_request and another sources for a current user
getLoginUrl() will build the login URL for you

Asking for permission using new PHP SDK (3.X.X)

How can I ask for permissions using new PHP SDK? I don't want to use the graph api and parse the url all the time. When the application is opened it should automatically ask for permissions if the user hasn't granted one already.
Here's how i'm doing it with the latest PHP SDK (3.0.1)
// init new facebook class instance with app info (taken from the DB)
$facebook = new Facebook(array(
'appId' => 'YOUR APP ID',
'secret' => 'YOUR APP SECRET'
));
// get user UID
$fb_user_id = $facebook->getUser();
// get the url where to redirect the user
$location = "". $facebook->getLoginUrl(array('scope' => 'publish_stream, email'));
// check if we have valid user
if ($fb_user_id) {
try {
// Proceed knowing you have a logged in user who's authenticated.
$fb_user_profile = $facebook->api('/me');
} catch (FacebookApiException $e) {
$fb_user_id = NULL;
// seems we don't have enough permissions
// we use javascript to redirect user instead of header() due to Facebook bug
print '<script language="javascript" type="text/javascript"> top.location.href="'. $location .'"; </script>';
// kill the code so nothing else will happen before user gives us permissions
die();
}
} else {
// seems our user hasn't logged in, redirect him to a FB login page
print '<script language="javascript" type="text/javascript"> top.location.href="'. $location .'"; </script>';
// kill the code so nothing else will happen before user gives us permissions
die();
}
// at this point we have an logged in user who has given permissions to our APP
// basic user info can be fetched easily
print "Welcome to my app". $fb_user_profile['name'];
Session Based Login with scope and Logout with access_token for PHP-SDK 3.2.0.
<?php
require './src/facebook.php';
$facebook = new Facebook(array(
'appId' => '135669679827333',
'secret' => 'xxxxxxxxxxxxxxxxxxxxxx',
));
$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;
}
}
if ($user) {
$params = array(access_token => ''.$access_token.'');
$logoutUrl = $facebook->getLogoutUrl($params);
} else {
$params = array(
scope => 'read_stream,publish_stream,publish_actions,read_friendlists',
//redirect_uri => $url
);
$loginUrl = $facebook->getLoginUrl($params);
};
$access_token = $_SESSION['fb_135669679827333_access_token'];
?>
.
<?php if($_SESSION['fb_135669679827333_access_token']): ?>
Login & Connect
<?php else: ?>
Login & Connect
<?php endif ?>

Categories