3

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

After page refreshAfter refresh

Console resultsConsole results

TommyBs
  • 9,354
  • 4
  • 34
  • 65
Kevin
  • 565
  • 12
  • 25

3 Answers3

2

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>
TommyBs
  • 9,354
  • 4
  • 34
  • 65
  • Didn't seem to do it unfortunately - UserId still reverts back to 0 after the refresh – Kevin Mar 26 '13 at 00:52
  • in fact it seems to be stuck in some sort of loop and keeps refreshing/reloading the page a couple times a second – Kevin Mar 26 '13 at 02:32
  • Try removing your call to header($loginUrl) . I think it might keep sending them to login url in your code if the authentication hasn't completed – TommyBs Mar 26 '13 at 07:37
  • Just did that, it's still auto refreshing itself.. obviously it has something to do with the window reloads .. it's almost like it does a reload, somewhere it reinitializes itself, the javascript get's called and finds out it needs to login, then starts the process over again – Kevin Mar 26 '13 at 10:33
  • I've read some things about facebook having issues with localhost, so I'm going to put it online this morning so I can rule that issue out.. – Kevin Mar 26 '13 at 11:21
  • That must have been it, because it's working now - thanks! take a look for yourself if you want - it's on bcbooks.bm/index_new.php – Kevin Mar 26 '13 at 11:40
  • Glad you sorted (most of) it out. Have you added the channel file? Otherwise it might be you need the header listed in the top answer here http://stackoverflow.com/questions/1835285/iframe-facebook-application-and-cookies-internet-explorer – TommyBs Mar 26 '13 at 15:54
  • yeah I (meaning you) sorted most of it! I have a channel file, but it's only one line with what was given by facebook docs, I'll take a look at that link now. – Kevin Mar 26 '13 at 15:56
  • Nope, that didn't work either unfortunately .. my channel file consists of: – Kevin Mar 26 '13 at 17:00
  • Did you try setting the header as mentioned in the post i linked to? – TommyBs Mar 26 '13 at 17:43
  • Yes, I used the meta tag - As well as adding headers: header('P3P:CP="IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT"'); – Kevin Mar 26 '13 at 17:51
  • W3C p3p Validator says the Compact Policy Syntax is ok http://validator.w3.org/p3p/20020128/p3p.pl?uri=http%3A%2F%2Fwww.bcbooks.bm – Kevin Mar 26 '13 at 17:58
1

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>
Fabio Antunes
  • 22,251
  • 15
  • 81
  • 96
  • Thanks for that - I added that, but still no dice. Whenever I refresh the page, UserId goes right back to 0. I don't need to reauthorize the app, I just need to hit login, but it certainly doesn't seem to remember.. – Kevin Mar 25 '13 at 18:27
  • Cookies are being set with that so that's good - perhaps I need to write some JS to check that cookie when each page loads? – Kevin Mar 25 '13 at 18:30
  • No, javascript SDK and PHP SDK handle that, do you have your project online? have you tried using the console of firebug or chrome to check if the javascript is being loaded properly? – Fabio Antunes Mar 25 '13 at 18:42
  • It's running off localhost , but I am online. The cookie is being set with the Java script and has values but it doesn't look like the values are being used? – Kevin Mar 25 '13 at 19:27
  • I added some screenshots of the console and what's happening before and after refresh – Kevin Mar 25 '13 at 19:57
0

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