Facebook PHP-SDK seems to lose userID after page refresh

半腔热情 提交于 2019-12-06 06:32:53

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>

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>

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

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