简体   繁体   English

页面刷新后 Facebook PHP-SDK 似乎丢失了用户 ID

[英]Facebook PHP-SDK seems to lose userID after page refresh

I've got login in working fine it seems, where I can login, accept the app (the first time) then display user information like name/picture/etc.我已经登录工作正常,我可以登录,接受应用程序(第一次)然后显示用户信息,如姓名/图片/等。

When I refresh the page however, userid goes back to 0 and I have to login again - I'm not sure what the problem is, I must be reinitiating it every time the page loads or something?然而,当我刷新页面时,userid 返回到 0,我必须再次登录 - 我不确定问题是什么,每次页面加载时我都必须重新启动它或其他什么? I dunno, I'll post some code- it might be tough as they are a bunch of separate files:我不知道,我会发布一些代码 - 这可能很难,因为它们是一堆单独的文件:

fb_login.php - fb_login.php -

<?php
    require_once("fb_login/facebook.php");
    $facebook = new Facebook(array(
      'appId' => 'APP_ID',
      'secret'=> 'APP_SECRET',
      'cookie'=> 'true'
    ));
    $userId = $facebook->getUser();

    if ($userId) {
        $userId = $facebook->getUser();
         echo("userID is: $userId");
}
    else{
        header("Location: {$loginURL}");
         echo("userId is: $userId");
    }


?>

navbar.php -导航栏.php -

<?php
              if($userId){
                 try {
                  $user_profile = $facebook->api('/me','GET');
                  echo '<li><a href="#">Welcome: ' . $user_profile['name'] . '</a></li>';
                  echo '<li><img src="https://graph.facebook.com/' . $user_profile['username'] . '/picture"><li>';
                  echo '<li class="divider-vertical"></li>';
                 } catch (FacebookApiException $e) {
                    $login_url = $facebook->getLoginUrl(); 
                    echo '<li>Please <a href="' . $login_url . '">login.</a></li>';
                    error_log($e->getType());
                    error_log($e->getMessage());
                 }
              }
              else{
                  echo '<li><a href="newUser.php">Sign Up</a></li>
                      <li class="divider-vertical"></li>';
              }
            ?>
<?php
                  if ($userId) { 
                    // echo("userID is: $userId");
                    // $params = array( 'next' => 'http://localhost/bcbooks-repo/index_new.php' );

                    $logoutUrl = $facebook->getLogoutUrl(); // $params is optional. 
                    echo '<li><a href="' . $logoutUrl . '">Log Out</a></li>';
                    $facebook->destroySession();
                  }
                  else{?>
<?php
                $userId = $facebook->getUser();
                $accessToken = $facebook->getAccessToken();
                $params = array(
                    'scope' => 'read_stream, friends_likes',
                    'redirect_uri' => 'http://localhost/bcbooks-repo/index_new.php'
                );

                $loginUrl = $facebook->getLoginUrl($params);
                echo '<a href="' . $loginUrl . '" class="btn btn-primary btn-block" type="button" id="sign-in-facebook">Sign In with Facebook</a>';
                                        ?>
<?php } ?>

index.php - index.php -

<?php
  require_once 'inc/FB_login.php';
require_once 'inc/navbar.php'; ?>

Logged in -登录 -登录

After page refresh页面刷新后刷新后

Console results控制台结果控制台结果

Building on top of what Fabio suggested try using this code (obviously replacing YOUR_APP_ID with your actual app id)在 Fabio 建议尝试使用此代码的基础上构建(显然将 YOUR_APP_ID 替换为您的实际应用程序 ID)

     <div id="fb-root"></div>
  <script>     

  window.fbAsyncInit = function() {
    FB.init({
      appId: 'YOUR_APP_ID', 
      status: true,
         cookie: true,
         xfbml: true,
       channelUrl:'/channel.html',
      frictionlessRequests: true,
      useCachedDialogs: true,
      oauth: true
    });
    FB.Event.subscribe('auth.login', function(response) {
      window.location.reload();
    });
    FB.Event.subscribe('auth.logout', function(response) {
      window.location.reload();
    });
  };
(function(d){
   var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
     if (d.getElementById(id)) {return;}
   js = d.createElement('script'); js.id = id; js.async = true;
      js.src = "//connect.facebook.net/en_US/all.js";
    ref.parentNode.insertBefore(js, ref);
     }(document));
      </script>

Although you're loading the facebook PHP SDK with the cookie option TRUE, the server side can't guess if the user is still logged on your website, or if he changed to another account, etc.尽管您使用 cookie 选项 TRUE 加载 facebook PHP SDK,但服务器端无法猜测用户是否仍在您的网站上登录,或者他是否已更改为其他帐户等。

If you want to retain the usar across all pages you must combine the javascript SDK with the PHP SDK.如果您想在所有页面上保留 usar,您必须将 javascript SDK 与 PHP SDK 结合使用。 To do that you just need to load the javascript SDK in each page you have, put this on every page that needs interaction with facebook right next to the <body> tag:为此,您只需在您拥有的每个页面中加载 javascript SDK,将其放在每个需要与 facebook 交互的页面的<body>标签旁边:

<body>
    <div id="fb-root"></div>
        <script>
          window.fbAsyncInit = function() {
            FB.init({
              appId      : 'YOUR_APP_ID', // App ID
              channelUrl : 'URL TO YOUR CHANNEL FILE', // Channel File Optional
              status     : true, // check login status
              cookie     : true, // enable cookies to allow the server to access the session
              xfbml      : true  // parse XFBML
            });

            // Additional initialization code here

            };


          // Load the SDK Asynchronously
          (function(d){
             var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
             if (d.getElementById(id)) {return;}
             js = d.createElement('script'); js.id = id; js.async = true;
             js.src = "//connect.facebook.net/en_US/all.js";
             ref.parentNode.insertBefore(js, ref);
           }(document));
    </script>

Try to declare userID in a cookie, just like this:尝试在 cookie 中声明 userID,就像这样:

$user = $facebook->getUser();
$expire=time()+60*60*24*30;
setcookie("user", $user, $expire);

For me it worked like a charm ;)对我来说,它就像一个魅力;)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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