Saturday, January 15, 2022

[FIXED] Facebook PHP SDK getuser (logout is another tab issue)

Issue

So basically as a simplified example I have 2 files. One is index.php file and one is logout.php file.

My index.php file contains something like this (I have cut out unnecessary lines of codes. Let's assume that the user has authenticated my app):

require_once "class/facebook/config.php";
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,
    'domain'    => REDIRECT_URI,
    ));

// Get User ID
$user = $facebook->getUser();
print_r($user);

So if I am logged into facebook and load this page, it basically prints user facebook id. Working well so far.

To logout let's say I use logout.php which contains something like,

require_once "class/facebook/config.php";

try{
    include_once "class/facebook/facebook.php";
}catch(Exception $e){
    error_log($e);
}

$facebook = new Facebook(array('appId'  => APP_ID, 'secret' => APP_SECRET, 'cookie' => true));
$facebook->destroySession();
header('location:'.REDIRECT_URI);

When I load this page I am logged out of facebook and my app, and am redirected to my index page. Going smoothly so far! Now since index.php loads and I am logged out 0 is printed. That looks good too.

Let's change the scenario a bit. Say we are logged in to facebook and we load index.php. Works well returns user id. Fine. Now let's say we open another tab, go to facebook.com. Then we log out from facebook.com directly.

Now when we refresh index.php in our previous tab, it still shows old user id when the user has actually already logged out of facebook!


Solution

Okay there is no easy way for this but I have solved this in a hacky way i.e. using javascript sdk to check if this is the same user. Here's how I have done this.

FB.api('/me', function(response) {
if (response.id){
       if (response.id == <?php echo $_SESSION['userid'];?>){

           // proceed with whatever you have to do

       }else{

           // user has changed or user has logged out separately from facebook
           alert("We don't know you anymore!");
           // code to proceed to logout or fire re-login option

       }
    }
}


Answered By - pewpewlasers

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.