Facebook Application with PHP running losing session - php

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..

Related

Facebook getUser() not working

I am trying to connect to the php facebook sdk and pull user data.
<?php
require_once('facebook-php-sdk/src/facebook.php');
// Create our Application instance (replace this with your appId and secret).
$facebook= new Facebook(array(
'appId' => '2453463636',
'secret' => '365653656565656',
'allowSignedRequest' => false,
));
$user = $facebook->getUser();
if ($user) {
try {
// Get the user profile data you have permission to view
// $user_profile = $facebook->api('/me');
$user_profile = $facebook->api('/me?fields=picture.width(100).height(100),first_name,last_name,username,email');
echo $user_profile['email'];
} catch (FacebookApiException $e) {
$user = null;
}
} else {
die('<script>top.location.href="'.$facebook->getLoginUrl().'";</script>');
}
?>
This works well on localhost while testing. I have a app created on facebook for this with a website platform added with the locahost as the site url in the dashboard.
To now test on the server I created another app on facebook with the domain and site url set as my staging site on my server.
I simply changed the appId and secret to that of the Facebook App created with the remote staging site url address, but this doesn't work.
Help Please! Is there something key that I missed in the code or dashboard that is not causing my page to get the user?
My page is a view in a codeigniter application, and require_once('facebook-php-sdk/src/facebook.php');, this directory resides in the root of my codeigniter application
EDIT:
I replace the die clause with die("failed");, and the text "failed" shows up when I try to load the page. Not sure what the problem is? This worked fine on localhost, why am I noy connecting now?
When I print_r($user); the page returns 0. Why am I not connecting.

$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.

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.

Facebook php sdk session logic

How i maintain a session cookie in my facebook app?
currently all of my pages have the code below:
$facebook = new Facebook(array(
'appId' => 'myid',
'secret' => 'mysecret',
'cookie' => true,
));
$session = $facebook->getSession();
$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(array('canvas' => 1,
'fbconnect' => 0,
'req_perms' => 'publish_stream,email',
'next' => 'register.php',
'cancel_url' => 'http://www.facebook.com/apps/application.php?id=MYAPPID&perms' ));
}
if (!$me){ print("<html><head>");
print("<script type=\"text/javascript\">function redirect(){ top.location.href = \"");
print($loginUrl);
print("\"; }</script></head>");
print("<body onload=\"redirect();\">Please wait...</body></html>"); exit(); }
This is wrong as i understand, i'm getting a new session each time a user navigate to a different page in my canvas. Do i need to use request? if so how do i accomplish that?
You're using the PHP SDK to fetch the user session, and that's okay. The PHP SDK is smart enough to set and utilize a cookie on the user which holds their session information - so you're not 'fetching' anything new from Facebook on every page load. You do need the redirect for install on every page just in case your user session does time out, or if the user uninstalls your app mid-use, or gets a direct link into a page of your application without being an installed user.
To make your code a little cleaner, you could move all the code to fetch the session & capture the installation from the user to a single script, and include it at the top of each page in your application. Then you don't have all that floating around, and you can easily change/tweak it when and if you need to.
edit: If your users are losing a session every time they navigate to a different page within your application, the user's browser might be blocking the cookie that the FB PHP SDK is setting because it's in an iframe. You probably need to set a P3P Policy header in your application, also, and this often fixes that problem.
<?php
header('P3P: CP="CAO PSA OUR"');

How can I allow users of my Facebook game to authorize the app without "Go to Facebook.com" logo?

I was following the tutorial here: http://net.tutsplus.com/tutorials/php/how-to-authenticate-your-users-with-facebook-connect/
But I can't get past the first step in allowing users to authorize my app. The app is at http://apps.facebook.com/freelancergame/ while the canvas URL is http://freelancer.xylotgames.com
I check via PHP whether there is an active session with the user. If it doesn't exist, I redirect the user to the login URL. Here is the code at the top of the page:
// Facebook library
require 'src/facebook.php';
// Create our Application instance
$facebook = new Facebook(array(
'appId' => 'xxxxxx',
'secret' => 'xxxxxxxxxxxx',
'cookie' => true,
));
// Let's see if we have an active session
$session = $facebook->getSession();
$me = null;
// Session based API call.
if (!empty($session)) {
// Active session; let's try getting the user ID and info
try {
$uid = $facebook->getUser();
$me = $facebook->api('/me');
} catch (FacebookApiException $e) {
error_log($e);
}
$logoutUrl = $facebook->getLogoutUrl();
print_r($user);
exit();
} else {
// There's no active session; let's generate one
$loginUrl = $facebook->getLoginUrl();
header('Location: ' . $loginUrl);
}
The thing is, upon visiting http://apps.facebook.com/freelancergame/ I am brought to a screen with the blue Facebook logo and a link saying "Go to Facebook.com".
However, if I allow the user to click a link to connnect with Facebook like so:
Connect
...the "Allow/Don't Allow" dialog shows up directly from Facebook's website, but if I click "Allow" or "Don't Allow", it goes directly to my canvas page (http://freelancer.xylotgames.com) instead of the embedded app page, which I'd prefer.
How can I get this to work? I see apps/games that use a pop-up instead of redirection. Is this preferred? If so, how would I do it? Why won't the NetTuts+ tutorial work for me when it most likely works for others?
I prefer the popup method (or iframe dialog inside Facebook), which you can open with the JS SDK:
Regular HTML popup: FB.login function. http://developers.facebook.com/docs/reference/javascript/fb.login/
Iframe dialog: FB.ui function. How to show the Extended Permission Dialog in FB using new Graph API?
For your redirection issue, I would double check the URLs in the configuration of the app.
I had this problem. I think the thing you need to change is the actual redirecting. Your login URL is loading inside the iframe, because that's all that headers can do. FB detects that and gives you a button to help break out of the frame. If you want to skip that, you need to redirect the top level of the browser to the login url.
Instead of header('Location: ' . $loginUrl); use:
die("<script type='text/javascript'>top.location.href = '" . $loginUrl. "';</script>");
It works perfectly for me, my app has completely seamless login and session refreshing. You can even spit this out during an ajax request that has an expired session, and it will get a new session for you.

Categories