Get facebook user if only logged in facebook php s

2019-03-04 11:58发布

I want to get current loggedin facebook user in php sdk. Here is what i have tried:

$facebook = new \Facebook(array(
        'appId' => 'XXXXXXXXXXX',
        'secret' => 'XXXXXXXXXXXXXXXXXXXXX',
    ));
$user = $facebook->getUser();
var_dump($user);
if ($user) {
   $logoutUrl = $facebook->getLogoutUrl();
   echo $logoutUrl;
} else {
   $loginUrl = $facebook->getLoginUrl();
   echo $loginUrl;
}

When I load the page with above code, I get the loginUrl even though I am logged in facebook. Only when i load $loginUrl in the browser, I am able to get facebook user.

How do I get the current user at first load of this page?

2条回答
Viruses.
2楼-- · 2019-03-04 12:40

Looks like you want to display the current user without him having approved your app to access his information.

This is not possible. Why?

  1. Using the Facebook API requires a token.
  2. A token is specific to a user, it means that a Facebook user needs to connect.
  3. The only way for a user to connect to Facebook is to go on Facebook.com and then enter his credentials. Since you agree with this, you will understand that your website must produce a link to redirect to Facebook.com.
  4. The user clicks on the link and is redirected to FB. Once connected to his account, he must allow your app from accessing his information. If done, the loop is therefore closed when Facebook.com successfully gives back an access token.

Unless you already have an access token, you can't bypass the login step. Thus, you must use the getLoginUrl() thing.

查看更多
Juvenile、少年°
3楼-- · 2019-03-04 12:46

I get the loginUrl even though I am logged in facebook.

Of course you do – being logged in to facebook.com is something completely different than being logged in to your app.

Only when i load $loginUrl in the browser, I am able to get facebook user.

That’s because after that the user is logged in to your application.

How do I get the current user at first load of this page?

Only possible for users who have connected to your app already at some point before, by using the JavaScript SDK.

查看更多
登录 后发表回答