简体   繁体   中英

Check if Facebook user is logged in to app with PHP SDK

I have an app using the Facebook Login API. I take the details of the user and store it in my own database and create my own user id for the user (I also store the facebook id).

Next time the user visits my site, I want to automatically set the session, without having them reconnecting again. So I want to get the Facebook ID of the user (If he is already authenticated) and then check in my database if that ID exists, if so then I set the session.

This is described in the Javascript SDK, however the problem with the Javascript SDK is that the user will not be logged in when visiting the first page, only after a page refresh (Since the Javascript is run after the PHP is executed, so the session is not set when the page loads).

So I want to do this server side, using the PHP SDK.

I tried the following code:

public function isUserLoggedIn(){
    $facebook = new Facebook();
    $user = $facebook->facebook->getUser();
    if($user){
        //Use API call for /me which require authentication
        try{
            $me = $facebook->facebook->api('/me');
            //If id_facebook exist, then set logged in session to user id
            if($me){
                $stmt = $GLOBALS['link']->prepare('SELECT * FROM users WHERE id_facebook=:id_facebook');
                $stmt->execute(array('id_facebook' => $me['id']));
                if($row = $stmt->fetch()){
                    $_SESSION['uid'] = $row['id'];
                }
            }
        } catch (FacebookApiException $e) {
            $user = null;
            //User is not logged in
        }
    }
}

This code only passes when the Javascript SDK has already authenticated the user and he is logged in. It does not work as intended.

So:

  • How do I use the PHP SDK to check if the user is authenticated with my App?

  • I could just set a $_COOKIE myself, is that the way to do it? I suppose that there is an "official" way using the SDK/API, since there is with the Javascript SDK.

I feel I'm a bit late, but here's my two cents:

I log into SO using facebook. Sometimes, in fact, after a day or so passed, i land on this site and after a second or two a little popup tells me that I've been logged in and to refresh the page. It's not really an issue, I just reload the page and I'm happy. That's what you're referring to.

But remember, should you only check the session to retrieve user's ID and facebook data, could lead to problems when the users logged out from facebook (or from your app): your session is not up-to-date with facebook.

That's why using Javascript SDK to login should be better.

I've done a lot of tests and trials today, to understand how the whole thing works (mainly because I encountered a lot of wrong or not complete information given by many "tutorials" out there). The version that did work is the one absolutely copy/pasted from Facebook guide to PHP SDK . Supposing there's an already configured Javascript SDK, I opened my index.php page and started with SDK inclusion:

//autoload is needed to include all sdk classes (not needed using Composer)
require_once ('./inc-fb-sdk/autoload.php');

Then, I had to explicitly tell the SDK to load some of the included classes; this is needed to make use of those classes:

use Facebook\FacebookJavaScriptLoginHelper;
use Facebook\FacebookRedirectLoginHelper;
use Facebook\FacebookRequest;
use Facebook\FacebookResponse;
use Facebook\FacebookSDKException;
use Facebook\FacebookSession;
use Facebook\FacebookRequestException;
use Facebook\GraphObject; 
use Facebook\GraphUser;

And, of course, we initialize PHP SDK creating the object (use your AppID and AppSecret in the following line):

FacebookSession::setDefaultApplication('App_id', 'App_secret');

Finally, this is the code from the Guide, with some added comments and echoes, to show if user is logged in or not:

//create object that is used to check login
$helper = new FacebookRedirectLoginHelper();
try {
  $session = $helper->getSessionFromRedirect();
} catch(FacebookRequestException $ex) {
  // When Facebook returns an error
} catch(\Exception $ex) {
  // When validation fails or other local issues
}

//show if the user is logged in or not
if ($session) {
  // Logged in
  echo ('User is logged in');
} else {
  echo ('User is not logged in');
}

Since you're already using the Login API, you only have to test loggin in/out from facebook and then refresh the page, to see the various situations that could happen.

And this should answer the two questions at the end of your post.

Hope this helps.

Note from @parse

You need to pass redirectUrl when you try to call FacebookRedirectLoginHelper(redirectUrl), otherwise you will get 'Missing argument' warning followed by this notice 'Undefined variable: redirectUrl in FacebookRedirectLoginHelper.php on line 77'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM