Facebook Connect PHP session variable won't set - php

I am using the Facebook PHP API 4.0 and trying to get the session variable to be set, so I can use the user's Facebook data.
The app, and Facebook approval page have all worked as expected, but the $session variable remains to be unset no matter what I try. I have tried to find the solution from similar questions on Stack with no success. This is the code I am using:
session_start();
//start fb login stuff
require_once( $config['basedir'].'/Facebook/FacebookSession.php' );
require_once( $config['basedir'].'/Facebook/FacebookRedirectLoginHelper.php' );
require_once( $config['basedir'].'/Facebook/FacebookRequest.php' );
require_once( $config['basedir'].'/Facebook/FacebookResponse.php' );
require_once( $config['basedir'].'/Facebook/FacebookSDKException.php' );
require_once( $config['basedir'].'/Facebook/FacebookRequestException.php' );
require_once( $config['basedir'].'/Facebook/FacebookAuthorizationException.php' );
require_once( $config['basedir'].'/Facebook/GraphObject.php' );
use Facebook\FacebookSession;
use Facebook\FacebookRedirectLoginHelper;
use Facebook\FacebookRequest;
use Facebook\FacebookResponse;
use Facebook\FacebookSDKException;
use Facebook\FacebookRequestException;
use Facebook\FacebookAuthorizationException;
use Facebook\GraphObject;
// init app with app id (APPID) and secret (SECRET)
FacebookSession::setDefaultApplication($fb_app, $fb_secret);
$helper = new FacebookRedirectLoginHelper( $config['baseurl'] );
try {
$session = $helper->getSessionFromRedirect();
} catch(FacebookRequestException $ex) {
// When Facebook returns an error
echo $ex;
} catch(\Exception $ex) {
// When validation fails or other local issues
echo $ex;
}
if ($session) {
echo 'Session var is finally being seen';
}
//end Facebook login stuff

The $session remains unset because you aren't logging the user in. You should modify the last part of the code to something like:
if ( isset( $session ) ) {
echo 'Session var is finally being seen';
} else {
// show login url
echo 'Login';
}
If the $session is not set, your code will ask the user to login. After they login, the $helper->getSessionFromRedirect(); part of your code should execute and set $session. See my tutorial on how to tackle this.
Edit:
If you are logging the user in from a different page, you need to make sure that $helper = new FacebookRedirectLoginHelper( '{your-url}' ); is the same on both pages. If they differ, then you will get a exception from the API related to redirect_uri mismatch.

Related

Why does "use" not work when included in php?

I'm updating my apps to work with the new PHP SDK, but I'm having this issue:
I want to do the Facebook stuff in a separate php file to keep things clean.
For example, this is my fb.php page:
<?php
require_once('sdk/autoload.php');
use Facebook\HttpClients\FacebookHttpable;
use Facebook\HttpClients\FacebookCurl;
use Facebook\HttpClients\FacebookCurlHttpClient;
use Facebook\Entities\AccessToken;
use Facebook\Entities\SignedRequest;
use Facebook\FacebookSession;
use Facebook\FacebookRedirectLoginHelper;
use Facebook\FacebookRequest;
use Facebook\FacebookResponse;
use Facebook\FacebookSDKException;
use Facebook\FacebookRequestException;
use Facebook\FacebookOtherException;
use Facebook\FacebookAuthorizationException;
use Facebook\GraphObject;
use Facebook\GraphSessionInfo;
// start session
session_start();
// init app with app id and secret
FacebookSession::setDefaultApplication(...,...);
// see if a existing session exists
if ( isset( $_SESSION ) && isset( $_SESSION['fb_token'] ) ) {
// create new session from saved access_token
$session = new FacebookSession( $_SESSION['fb_token'] );
// validate the access_token to make sure it's still valid
try {
if ( !$session->validate() ) {
$session = null;
}
} catch ( Exception $e ) {
// catch any exceptions
$session = null;
}
}
// see if we have a session
if ( isset( $session ) ) {
// save the session
$_SESSION['fb_token'] = $session->getToken();
// create a session using saved token or the new one we generated at login
$session = new FacebookSession( $session->getToken() );
//logged in
} else {
//user is not logged in
?>
<script>window.location="...link to login page...";</script>
<?php
exit;
}
A page which uses the Facebook session, could look like this (testing.php):
<?php
require_once('fb.php');
$request = new FacebookRequest( $session, 'GET', '/me' );
$response = $request->execute();
$graphObject = $response->getGraphObject()->asArray();
echo "Welcome, ".$graphObject['first_name'];
This returns this error:
Fatal error: Class 'FacebookRequest' not found
The code works fine when I put use Facebook\FacebookRequest; in testing.php , but I don't want to do that, since that was the point of putting all the Facebook session stuff in a separate fb.php file...
What is the reason for this, and is there a solution how to keep all my Facebook stuff in a separate file?
Thanks!
File in which you are including fb.php is in different scope so can't use that imports.
You have to specify them again.
You can read more about that in PHP manual.

Getting all members list (from a group I own) using Facebook Graph API - doesn't get the whole list - What part is wrong in my code?

I started working with the Facebook Graph API and noticed that when trying to get all the member list from my group (that I own), echo-ed the user name and I get only (around) 4900 users as an output - I have 15K+ users in my group!!!
To test that I var_dump-ed every list and it gave me 127 arrays with the text "more elements..." so I concluded that echoing the list was good, but getting the lists was wrong.
I tried to get the members list using the Graph API Explorer and it gave the same results with wrong "next" links with strange offset and limit parameters that don't make any sense and that I didn't enter.
This is my code for now (scroll to "Cool Stuff Here"):
<?php
session_start();
require_once( 'Facebook/FacebookSession.php' );
require_once( 'Facebook/FacebookRedirectLoginHelper.php' );
require_once( 'Facebook/FacebookRequest.php' );
require_once( 'Facebook/FacebookResponse.php' );
require_once( 'Facebook/FacebookSDKException.php' );
require_once( 'Facebook/FacebookRequestException.php' );
require_once( 'Facebook/FacebookAuthorizationException.php' );
require_once( 'Facebook/GraphObject.php' );
require_once( 'Facebook/GraphUser.php' );
require_once( 'Facebook/GraphSessionInfo.php' );
require_once( 'Facebook/HttpClients/FacebookHttpable.php' );
require_once( 'Facebook/HttpClients/FacebookCurl.php' );
require_once( 'Facebook/HttpClients/FacebookCurlHttpClient.php' );
require_once( 'Facebook/Entities/AccessToken.php' );
require_once( 'Facebook/Entities/SignedRequest.php' );
use Facebook\GraphUser;
use Facebook\FacebookSession;
use Facebook\FacebookRedirectLoginHelper;
use Facebook\FacebookRequest;
use Facebook\FacebookResponse;
use Facebook\FacebookSDKException;
use Facebook\FacebookRequestException;
use Facebook\FacebookAuthorizationException;
use Facebook\GraphObject;
use Facebook\Entities\AccessToken;
use Facebook\HttpClients\FacebookCurlHttpClient;
use Facebook\HttpClients\FacebookHttpable;
$app_id = '13434480350553256103140350';
$app_secret = 'a866dcd372123fc87373a345cvvf34d0e70c3cdf0vvc13db4521basdd99';
$redirect_url = 'http://localhost/test/YellowSpider/src/';
FacebookSession::setDefaultApplication( $app_id, $app_secret );
//helper for redirect
$helper = new FacebookRedirectLoginHelper($redirect_url);
// Requested permissions for the app - optional
$permissions = array(
'email',
'user_location',
'user_birthday',
'user_groups'
);
// Check if existing session exists
if ( isset( $_SESSION ) && isset( $_SESSION['fb_token'] ) ) {
// Create new session from saved access_token
$session = new FacebookSession( $_SESSION['fb_token'] );
// Validate the access_token to make sure it's still valid
try {
if ( ! $session->validate() ) {
$session = null;
}
} catch ( Exception $ex ) {
// Catch any exceptions
$session = null;
}
} else {
// No session exists
try {
$session = $helper->getSessionFromRedirect(); ////Processes the redirect data from Facebook, if present. Returns a FacebookSession or null.
} catch( FacebookRequestException $ex ) {
// When Facebook returns an error
} catch( Exception $ex ) {
// When validation fails or other local issues
echo $ex->message;
}
}
// Check if a session exists
if ( isset( $session ) ) {
// Save the session
$_SESSION['fb_token'] = $session->getToken();
// Create session using saved token or the new one we generated at login
$session = new FacebookSession( $session->getToken() );
/********************************* Cool Stuff Here *****************************************/
$request = new FacebookRequest($session, 'GET', '/1501313558474010996619/members'); //Represents a request that will be made against the Graph API.
//From the response - get graph object
$response = $request->execute(); //Returns a Facebook\FacebookResponse from this request, from which a strongly-typed result can be retrieved.
//Throws an exception if the request fails. If the error is returned from Facebook,
//as opposed to a networking issue, a Facebook\FacebookRequestException is thrown.
$graphObject = $response->getGraphObject()->asArray();
var_dump($graphObject);
while($response){
var_dump($graphObject['data']);
//echo $members['id'];
if($response->getRequestForNextPage() != null){
$response = $response->getRequestForNextPage()->execute();
var_dump($response->getRequestForNextPage());
continue;
}else{
break;
}
}
/********************************* END Cool Stuff Here *****************************************/
// Create the logout URL (logout page should destroy the session)
$logoutURL = $helper->getLogoutUrl( $session, 'http://localhost/test/YellowSpider/src/' );
session_destroy(); // added this, clears all sessions.
echo 'Log out';
} else {
// No session
// Get login URL
$loginUrl = $helper->getLoginUrl( $permissions );
echo 'Log in';
}
What can be my problem? Is my code written ok? Might it be a temporary problem with Facebook?
With my experience with PHP, using GET and POST, GET is kinda limited when passing parameters while POST is not, But with the FB API I guess there isn't any connection to this because the POST method there is used for literally, post things on Facebook (?)
It's a known Facebook bug (for more than 2 years) in a low priority fix.
To bypass this I think scrapping is the only best option, nevertheless, https://www.facebook.com/apps/site_scraping_tos_terms.php

Facebook SDK for PHP 4.0.0 login logout issue

I am a PHP developer and what I want is firstly user come to my website and login using Facebook login then I want to redirect user to specific page and get access token and then call to Graph API to access user's data. I have divided it into 2 steps
1) Make user to login using Facebook, It's done and code is given below:
include_once('facebook-php-sdk-v4-master/src/Facebook/FacebookSession.php');
include_once('facebook-php-sdk-v4-master/src/Facebook/FacebookRedirectLoginHelper.php');
require_once( 'facebook-php-sdk-v4-master/src/Facebook/FacebookRequest.php' );
require_once( 'facebook-php-sdk-v4-master/src/Facebook/FacebookResponse.php' );
require_once( 'facebook-php-sdk-v4-master/src/Facebook/FacebookSDKException.php' );
require_once( 'facebook-php-sdk-v4-master/src/Facebook/FacebookRequestException.php' );
require_once( 'facebook-php-sdk-v4-master/src/Facebook/FacebookAuthorizationException.php' );
require_once( 'facebook-php-sdk-v4-master/src/Facebook/GraphObject.php' );
use Facebook\FacebookSession;
use Facebook\FacebookRedirectLoginHelper;
use Facebook\FacebookRequest;
use Facebook\FacebookResponse;
use Facebook\FacebookSDKException;
use Facebook\FacebookRequestException;
use Facebook\FacebookAuthorizationException;
use Facebook\GraphObject;
session_start();
FacebookSession::setDefaultApplication('APP id', 'APP key');
$helper = new FacebookRedirectLoginHelper('http://redirect-url.com/');
$loginUrl = $helper->getLoginUrl();
echo "FB login here";
2) Get token detail on redirect URL, which is incomplete
Can anyone please help me how can I get this detail ?????
See the following tutorial on how to handle login and sessions correctly.
To get the token after redirect, you need to so the following:
$session = $helper->getSessionFromRedirect();
Then, check if the session is valid and redirect as needed:
if ( isset( $session ) ) {
// user is logged in, display logout link
echo 'Logout';
} else {
// show login url
echo 'Login';
}
Even I was going getting the same error.
Found another method to get session information on another page.
On first page
FacebookSession::setDefaultApplication($app_id,$app_secret,$cookie);
// login helper with redirect_uri
$helper = new FacebookCanvasLoginHelper();
try {
$session = $helper->getSession();
$_SESSION['token'] = $session->getToken();
}
On the second page it should be
$token = $_SESSION["token"];
$session = new FacebookSession($token);

Class 'FacebookSession' not found - API Facebook 4.0

i'm trying the new Facebook API (4.0) and I have serious problem with this.
The code of my page loginUser.php is:
<?php
require_once("autoload_fb.php");
// init app with app id and secret
FacebookSession::setDefaultApplication( '647345538685342','6ea4dc94874b31a637b6fe368bcfba76' );
// login helper with redirect_uri
$helper = new FacebookRedirectLoginHelper( 'http://www.radiobrunoestate.mumbleserver.it/api/loginUser' );
// see if a existing session exists
if ( isset( $_SESSION ) && isset( $_SESSION['fb_token'] ) ) {
// create new session from saved access_token
$session = new FacebookSession( $_SESSION['fb_token'] );
// validate the access_token to make sure it's still valid
try {
if ( !$session->validate() ) {
$session = null;
}
} catch ( Exception $e ) {
// catch any exceptions
$session = null;
}
} else {
// no session exists
try {
$session = $helper->getSessionFromRedirect();
} catch( FacebookRequestException $ex ) {
// When Facebook returns an error
} catch( Exception $ex ) {
// When validation fails or other local issues
echo $ex->message;
}
}
// see if we have a session
if ( isset( $session ) ) {
// save the session
$_SESSION['fb_token'] = $session->getToken();
// create a session using saved token or the new one we generated at login
$session = new FacebookSession( $session->getToken() );
// graph api request for user data
$request = new FacebookRequest( $session, 'GET', '/me' );
$response = $request->execute();
// get response
$graphObject = $response->getGraphObject()->asArray();
// print profile data
echo '<pre>' . print_r( $graphObject, 1 ) . '</pre>';
// print logout url using session and redirect_uri (logout.php page should destroy the session)
echo 'Logout';
} else {
// show login url
echo 'Login';
}
?>
and the autoload_fb.php is simply:
<?php
session_start();
require_once( 'Facebook/FacebookSession.php' );
require_once( 'Facebook/FacebookRedirectLoginHelper.php' );
require_once( 'Facebook/FacebookRequest.php' );
require_once( 'Facebook/FacebookResponse.php' );
require_once( 'Facebook/FacebookSDKException.php' );
require_once( 'Facebook/FacebookRequestException.php' );
require_once( 'Facebook/FacebookAuthorizationException.php' );
require_once( 'Facebook/GraphObject.php' );
use Facebook\FacebookSession;
use Facebook\FacebookRedirectLoginHelper;
use Facebook\FacebookRequest;
use Facebook\FacebookResponse;
use Facebook\FacebookSDKException;
use Facebook\FacebookRequestException;
use Facebook\FacebookAuthorizationException;
use Facebook\GraphObject;
?>
I get this error on first server:
Fatal error: Class 'FacebookSession' not found in /home/jack/provaprova/api/loginUser.php on line 6
Testing the same code on another Server i have this error:
Parse error: syntax error, unexpected T_OBJECT_OPERATOR in /home/eyikmdnu/public_html/jack/provaprova/api/Facebook/FacebookSession.php on line 140
Where could be the problem? could be a problem of the server configuration?
Thanks
Facebook PHP SDK v4 requires PHP 5.4. You are most likely using an older version of PHP.
I think you have to put the "use" statements also in the top of the "loginUser.php" file.
Suppose you've already made it work, but I think that was the problem.
Maybe this can help someone else.
Your use statements from the include file won't import them for the main file. So you'll need to move the use statements to your main file right after your include of the autoload_fb.php file.
But then you'll have another issue. Your autoloader isn't a real autoloader. Here's more info on that.

Facebook PHP SDK 4.0 Login

I am trying to get Facebook login with their new PHP SDK 4.0 working for my site. I followed their gist almost verbatim and still can't even get a test page to work. When I try to log in, I get redirected to a url of the form:
https://www.facebook.com/v2.0/dialog/oauth?client_id={some number}&redirect_uri{localhost%2F%7E{MyName}%2F{my site}}&state=08d94ec4670256aa2b2c586781590766&sdk=php-sdk-4.0.0&scope=
I have filled out the same url on my Facebook developer page already, and this is the code I am trying to test:
<?php
require_once( 'Facebook/FacebookSession.php' );
require_once( 'Facebook/FacebookRedirectLoginHelper.php' );
require_once( 'Facebook/FacebookRequest.php' );
require_once( 'Facebook/FacebookResponse.php' );
require_once( 'Facebook/FacebookSDKException.php' );
require_once( 'Facebook/FacebookRequestException.php' );
require_once( 'Facebook/FacebookAuthorizationException.php' );
require_once( 'Facebook/GraphObject.php' );
use Facebook\FacebookSession;
use Facebook\FacebookRedirectLoginHelper;
use Facebook\FacebookRequest;
use Facebook\FacebookResponse;
use Facebook\FacebookSDKException;
use Facebook\FacebookRequestException;
use Facebook\FacebookAuthorizationException;
use Facebook\GraphObject;
// start session
session_start();
// init app with app id and secret
FacebookSession::setDefaultApplication( '{My app ID}','{My app secret}' );
// login helper with redirect_uri
$helper = new FacebookRedirectLoginHelper('localhost/~{My Name}/{My Project}' );
try {
$session = $helper->getSessionFromRedirect();
} catch( FacebookRequestException $ex ) {
// When Facebook returns an error
} catch( Exception $ex ) {
// When validation fails or other local issues
}
// see if we have a session
if ( isset( $session ) ) {
// graph api request for user data
$request = new FacebookRequest( $session, 'GET', '/me' );
$response = $request->execute();
// get response
$graphObject = $response->getGraphObject();
// print data
echo '<pre>' . print_r( $graphObject, 1 ) . '</pre>';
} else {
// show login url
echo 'Login';
}
Unfortunately, I never get redirected back, or even load the login page. What could I be doing wrong here?
I had the same problem.
You need to set a domain URL and site URL in your Facebook App settings first. Go to this page to change your setting: https://developers.facebook.com/apps.
I have shared a step by step here.
You don't have to include the php files. Facebook wants you to use composer to manage what is required.
However.... they give you a workaround: Include autoload.php and keep the file structure they give you for easiest implementation. For ease, put all the files from the SDK into a folder called facebook, so you have a sub folder in there called src and within that another one called Facebook
Then the SDK creates a link that your users can click on to authorize access to your app.
If you are testing, you need to keep deleting the app from your facebook profile to get the signup window each time (Settings top right dropdown, then Apps on left as of Aug 2014), otherwise it will bounce straight through to your specified redirect page and will appear as if nothing worked.
// if you include this file you don't need to use composer
require_once('facebook/autoload.php');
// use these
use Facebook\FacebookSession;
use Facebook\FacebookRedirectLoginHelper;
// initiate the session
FacebookSession::setDefaultApplication('[YOUR ID]', '[YOUR SECRET]');
// use the helper
$helper = new FacebookRedirectLoginHelper('[YOUR REDIRECT URL]');
// get a loginurl
$loginUrl = $helper->getLoginUrl();
echo "<a href='".$loginUrl."'>Link here</a>";
Notes to check:
Check you have set up a test app on facebook.
Check the domain matches the one you are using.
Check the full url for the redirect page that you will be using to handle the response.
The script is not complete. You have to write the else part where if the session is not set. Request for permission comes to role here.
else {
$helper = new FacebookRedirectLoginHelper('https://apps.facebook.com/yourappname/');
$permissions = array(
scope =>'publish_actions',
'email',
'user_location',
'user_birthday'
);
// Get login URL
$auth_url = $helper->getLoginUrl($permissions);
//$auth_url = $helper->getLoginUrl(array('email'));
echo "<script>window.top.location.href='".$auth_url."'</script>";
As stated in the Facebook Developer documentation, you need PHP 5.4+.
Is this the code you are using?
$helper = new FacebookRedirectLoginHelper('localhost/~{My Name}/{My Project}' );
You will be redirected from Facebook, so the argument here needs to be a URL accessible from the Internet.
I was having problem when trying to execute
$loginUrl = $helper->getLoginUrl();
The solution was to call:
session_start();
before the
$helper = new FacebookRedirectLoginHelper($redirect_url);
on #DigitalVisual's answer above.
$helper = new FacebookRedirectLoginHelper('localhost/~{My Name}/{My Project}');
Use like:
$helper = new FacebookRedirectLoginHelper('http://example.com/help.php');
Must use full URL.

Categories