Facebook PHP-SDK seems to lose userID after page refresh

浪尽此生 提交于 2019-12-08 01:49:07

问题


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? I dunno, I'll post some code- it might be tough as they are a bunch of separate files:

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
              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 -

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

Logged in -

After page refresh

Console results


回答1:


Building on top of what Fabio suggested try using this code (obviously replacing YOUR_APP_ID with your actual app 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>



回答2:


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.

If you want to retain the usar across all pages you must combine the javascript SDK with the 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:

<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>



回答3:


Try to declare userID in a cookie, just like this:

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

For me it worked like a charm ;)



来源:https://stackoverflow.com/questions/15621586/facebook-php-sdk-seems-to-lose-userid-after-page-refresh

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!