How to check if a user is logged in to facebook - php

I am totally new to facebook api and I wanted to ask , whats the easiest and fastest way to know if a person is logged in to facebook.
One solution that I tought of is to send a javascript or php request and see if i get some status code that tells me whether the person is logged in or not (say if it returns 404, then that means he isnt logged in).
update:
I found this easy "hack":
function logged() {
alert('logged');
}
function notlogged() {
alert('not logged');
}
</script>
<script src="http://www.facebook.com/ajax/composer/attachment/question/question.php" onload="logged()" onerror="notlogged()">
But it doesnt work... however, thats the type of code that i am looking for..code that would send a request and if fails, it will throw an error
**update**
I dont want to trigger any suspicion from the user that I am checking if he is logged in. So if there is a use of app_id, then I would think that I need the users permission to use my app..that is a burden cause I will have to take another authentication step.
I cant have the user know that he is being authenticated in any way regarding facebook

If I am reading your code correctly, only if no session is returned do you do the redirect? According to comments in Facebook's example: http://github.com/facebook/php-sdk/blob/master/examples/example.php (great place to this info huh?), even if you get a session back, you can't assume it's still valid. Only trying an API call that requires a logged in user will you know for sure. This is the best way I've seen to reliably determine login/logout status.
if ($session) {
try {
$me = $facebook->api('/me');
if ($me) {
//User is logged in
}
} catch (FacebookApiException $e) {
//User is not logged in
}
}

try This, Hope this will help
include 'facebook.php';
$facebook = new Facebook(array(
'appId' => $app_id, // your application id
'secret' => $app_secret, // your application secret
'cookie' => false,
));
$user = $facebook->getUser();
$loginUrl = $facebook->getLoginUrl(
array(
'scope' => '// put your permission'
)
);
if ($user) {
try {
// Proceed knowing you have a logged in user who's authenticated.
$permissions = $facebook->api('/me/permissions');
} catch (FacebookApiException $e) {
$user = null;
}
}
if (!$user) {
echo "<script type='text/javascript'>top.location.href = '$loginUrl';</script>";
}

If you have a facebook "tab" then limited user information is provided to you as part of the signed_request. And for a facebook tab, you need to create an app.
Otherwise, without an App ID and alerting the user YOU CANNOT DO IT.
There have been hacks in the past, some of the cleverer ones have been to put up comment boxes and measure the hieght of the containing DIV (they used to be larger if logged in) or to include the facebooks FBML tabs to show a log in button (log in was wider) but theses were all stamped out as they were discovered. The same probably goes for the link you tried in your question.
Facebook, for all the debate on rpivacy, won't knowlingly leak information - until you get an app id, ask the user then you can get nearly everything...

Check this topic: https://stackoverflow.com/a/10698594/1789650
This should answer your question. You have to load the javascript SDK to get it to work correctly.

Related

I pass Facebook different URLs on a website and they return the same data each time?

I have a problem with requesting data from Facebook. I have tried a few different ways to get the number of likes for an individual page on a website that I manage, but each time I send a specific URL I get the same information back. The share and like and comment totals are the same for each URL that I pass to Facebook.
So for instance I send:
http://api.facebook.com/restserver.php?method=links.getStats&urls=http://thiswebsite.com/page21/
or
http://api.facebook.com/restserver.php?method=links.getStats&urls=http://thiswebsite.com/page49/
and I get the same information returned.
I have Open Graph tags on the site and I think they are implemented correctly but even when I pass URLs directly as show above I get the same results. Could the og tags I have on the site be effecting the results Facebook returns, even if I am manually passing them to Facebook?
Well you have two options to take. One's overly complicated but once you have it working you'll never have to worry about it. The other takes some time but requires a lot less effort.
I'll start with the simple one. Go to https://developers.facebook.com/tools/explorer. Once you get there your uid should already be there just delete every thing after it including the ? and paste in
/accounts?fields=id,name,likes
You will have to make and access token to see the data. You need the manage_pages permission checked on the extend permissions tab.
Once you do that hit submit and you should see in the results all the pages you're admin on the UID of the page, name and number of likes.
The other way is to build an app that handles this for you. Which you will have to register with Facebook and get an app id from them. With that app you can build a program that gets the information for you using php and or java script
Here's a sample of some php you can use.
require "facebook.php";
$config = array(
'appId' => 'app_id',
'secret' => 'app_secret',
'fileUpload' => false, // optional
'allowSignedRequest' => false, // optional, but should be set to false for non-canvas apps
);
$facebook = new Facebook($config);
$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 {
$path = '/' .$pageId .'?fields=likes';
$pageData = $facebook->api($path,'GET');
$likes = $pageData['likes'];
} 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
// just ask the user to login again here.
error_log($e->getType());
error_log($e->getMessage());
}
} else {
// No user, print a link for the user to login
$login_url = $facebook->getLoginUrl();
}
If you choose the longer route let me know I have this whole thing already built.

$facebook -> getUser() returns wrong value?

The question is the same as title. I'm using the latest php-sdk (v3.1.1) to operate server-side authentication flow.
I have 2 tabs in Chrome, one is my Facebook page and the other is php test page. These 2 problems happen many times:
$facebook->getUser() still returns 0 even when I logged in.
$facebook->getUser() still returns an ID even when I logged out.
I have to do a work-around of this: try initiating a graph API request with provided access_token, and check if $response->error->type == "OAuthException" to ensure there's an active session or not.
Is there any way to use $facebook->getUser() "stably"? I've searched a lot through SO but not found best answer for php-sdk 3.1.1 yet.
Highly appreciate any helps. Thanks.
Login.
As per documentation example of FB SDK, getUser() returns userId even when you're logged out, but have cookies associated with FB account.
To detect is user logged in you should use
$user = $facebook->getUser();
//Check Access token
if ($user) {
try {
$user_profile = $facebook->api('/me');
} catch (FacebookApiException $e) {
$user = null;
}
}
if ($user) {
//logged-in
} else {
//not logged-in
}
To login in your app make user logs in in your app, not on neighbouring tab, by following this url (make sure that you're passing the scope based on intended actions performed by your app):
$loginUrl = $facebook->getLoginUrl(
'scope' => ...
);
Logout. Seems that your PHP server is storing some values of access tokens per session, so even when you're logged out in your browser, your server still have these tokens valid. Actually, I don't know, is it bug or feature, but they're not destroyed by Facebook after user logout.
To destroy these tokens I'm using these:
$facebook->destroySession();
I'm calling it every time when user logs-out by $facebook->getLogoutUrl();

Facebook connect is very slow, can I use AJAX?

I'm implementing the facebook php sdk and using it for user login/connect.
Everything works as expected, however, at the top of each page, I need to call
$facebook->api('/me') to determine if the user is logged in or not..
This call is very slow, sometimes, taking up to 2 seconds to return.
So, any interaction by the user, always has a 1-2 sec delay before any page loads..
I suspect, it's because, the $facebook->api('/me') call is using httpS ..
Any suggestions....
$facebook = new Facebook(array( 'appId' => 'xxxxxxxxxxxxxxx', 'secret' => 'xxxxxxxxxxxxxxxxx',));
$user = $facebook->getUser();
if ($user)
{
try { $user_profile = $facebook->api('/me','GET'); }
catch (FacebookApiException $e) { error_log($e); $user = null; }
}
$login_parms = array('scope' => 'user_birthday', 'redirect_uri' => 'http://xxx.com/login');
$login_link = $facebook->getLoginUrl($login_parms);
if($user)
{
/* logged in */
}
else
{
/* not */
}
You really shouldn't perform the Facebook API request on each page load. Only do it once when the user logs in. Then you can store the "logged in" flag in the session (or a signed cookie).
If you need to store e.g. some of the user's facebook profile information, also put it in the session or your database.
Add some spinning wheel where login form is, then call ajax on document ready to your php script, script returns false or loged in user data (or more data if you need - redirect url) and then depending on result show form to login or display currently loged in user.
What i mean Javascript will handle all logic depending on what is returned from server, redirects, change UI etc.
Another way is to cache (session with expiration) first call to facebook if user is loged in remember it. And check if that Session variable is present and not yet expired. Only call again when doing some sensitive tasks or get expired.
If you do not need to get "fresh" values from $facebook->api("/me").
Then I would suggest you cache the response, if you use any PHP-framework (eg. Zend, Yii, Codeigniter) this should be really straight forward.
If you're not using a PHP-framework i suggest you still look into the excellent ZF documentation for their cache solution.
Zend Framework - Cache
If you, however, need fresh values each load you can make a simple page that only returns the $facebook->api("/me") part and returns it as bare HTML. Then simply keep a or similar that recieves the response when it's finished.
An easy solution would be using jQuery and just write:
$("#div-id").load("/page-that-returns-facebook-api-me-result");

Get users' authorization to run my application and access their full name

How do I get users' authorization to run my application and access their full name any time I need it? The following is a file included on top of all my application files. In reality, it don't even ask for users' authorization to run as other applications do (like CittyVille and others).
<?php
include_once 'facebook/facebook.php';
$facebook = new Facebook(array(
'appId' => 'APPID',
'secret' => 'APPSECRET'
));
$user = $facebook->getUser();
if($user)
{
try
{
$me = $facebook->api('/me?fields=id,name,locale');
}
catch(FacebookApiException $e)
{
error_log($e);
$user = null;
}
}
if($user)
$logoutUrl = $facebook->getLogoutUrl();
else
$loginUrl = $facebook->getLoginUrl();
Can anyone say me the right way for doing the request?
Ill answer this because I think the documentation for the PHP API is, well non existent and the example they give you, which is what you are using, isn't that great. Though I do think a few moments of Google-ing would of given you the answer.
You are correct, it is not logging the user in.
It is however checking to see if the user is logged in already, which if it is is getting the users profile information and generating a link to logout.
If the user is not logged in it is generating a link the user will need to click on in order to log in to your site, and give your site permissions to access the account.
As far as what permissions your application requires, you need to put that information in the ->getLoginUrl() call so that facebook knows what permissions you require. You can find information on the permissions you can pass at http://developers.facebook.com/docs/reference/api/permissions/
Once the person has clicked on the link generated, it takes them to facebook, asks them to login and grant your website permissions, then redirects either back to the page it came from, or to another page (depending on what you tell it in the getLoginUrl call). At this point a user is now logged in to your site, and you can run use the API to get information.
Alternately, once you have the address they need to go to in order to log in, you can use php's header function to redirect them to this page without them having to actually click the a link.

Facebook API - Session still exists after user logout

I am using Facebook php-sdk in my iframe facebook app to get user login status.
Right after I sign out using facebook Account > Log out link, the session is not destroyed yet. I must wait a few minutes before old session expires, then my app will again get the correct login status.
I expect the facebook to kill itself and the session when user signs out. How do I manually kill the session?
Here is my code:
$initParams = array(
'appId' => $conf['app_id'],
'secret' => $conf['secret_api_key'],
'cookie' => TRUE,
);
$fb = new Facebook($initParams);
$fb->getSession(); // will return a session object eventhough user signed out!
SOLVED:
calling $fb->api('/me') will destroy the session if user has previously logged out.
I've changed my code as following:
if ($session)
{
try
{
$fbuid = $fb->getUser();
$me = $fb->api('/me');
}
catch(FacebookApiException $e){}
}
If the API call is unsuccessful, $session will be set to NULL. Very weird behavior, I don't explain everything that is going on here but it solved my problem of having residual session object not being updated via getSession() method.
I'm using $fb->getUser() and what I did was almost identical with yours.
if ($fb->getUser())
{
try
{
$me = $fb->api('/me');
}
catch(FacebookApiException $e){
**$fb->destroySession();**
}
}
I found that using only API to check whether FB is logged out or not sometimes is inconsistent, but with destroySession(), the session will surely be destroyed.
if you are using the javascript FB.INIT calls on the login page, then set status to false from true.
details about the status attribute :
http://developers.facebook.com/docs/reference/javascript/FB.init/
Try finding the formatData function somewhere at LoginWindow (AS3) and find this line:
vars.redirect_uri = FacebookURLDefaults.LOGIN_SUCCESS_URL
Change the value for http://www.facebook.com/ and logout from that html page when logged in.
This is a temporary solution to logout if you are developer, not the end user.
Facebook should disassociate the session from the account that the session belonged to. You can use Facebook::getUser() to check whether this was done:
if ($fb->getUser() === null) {
// User logged out
} else {
// User logged in
}
Try $facebook->setSession(null) or using javascript Logout
Logout does not work any way you do.
Try posting this link in your browser, after you log in to facebook.
https://www.facebook.com/logout.php
What happen? it takes you to your facebook. No logout at all.
What ever you do, check the function (depends on your API) handleLogout and check the output. In my case, it returns the entire facebook html page.
The only way I've managed to solve this problem was by clearing the session using the signed request to check the user id:
$facebook = Membership::getFacebookApp();
$signed_request = $facebook->getSignedRequest();
if(isset($_SESSION['facebook_id']) && $signed_request['user_id'] != (int)$_SESSION['facebook_id']){
$_SESSION = array();
}

Categories