Filip Glazar Filip Glazar - 4 months ago 27
PHP Question

Howto: Persistent login via Facebook Connect

I would need a persistent login on my site where I am using FB Connect to log in via FB. I use PHP SDK 3. Is there any way how to make persistent login? I think, that I will have to combine PHP SDK and JS SDK, but I have no idea how to do it.

Answer

The PHP-SDK example file with_js_sdk.php provides a good start for you:

<?php

require '../src/facebook.php';

$facebook = new Facebook(array(
  'appId'  => '191149314281714',
  'secret' => '73b67bf1c825fa47efae70a46c18906b',
));

// See if there is a user from a cookie
$user = $facebook->getUser();

if ($user) {
  try {
    // Proceed knowing you have a logged in user who's authenticated.
    $user_profile = $facebook->api('/me');
  } catch (FacebookApiException $e) {
    echo '<pre>'.htmlspecialchars(print_r($e, true)).'</pre>';
    $user = null;
  }
}

?>
<!DOCTYPE html>
<html xmlns:fb="http://www.facebook.com/2008/fbml">
  <body>
    <?php if ($user) { ?>
      Your user profile is
      <pre>
        <?php print htmlspecialchars(print_r($user_profile, true)) ?>
      </pre>
    <?php } else { ?>
      <fb:login-button></fb:login-button>
    <?php } ?>
    <div id="fb-root"></div>
    <script>
      window.fbAsyncInit = function() {
        FB.init({
          appId: '<?php echo $facebook->getAppID() ?>',
          cookie: true,
          xfbml: true,
          oauth: true
        });
        FB.Event.subscribe('auth.login', function(response) {
          window.location.reload();
        });
        FB.Event.subscribe('auth.logout', function(response) {
          window.location.reload();
        });
      };
      (function() {
        var e = document.createElement('script'); e.async = true;
        e.src = document.location.protocol +
          '//connect.facebook.net/en_US/all.js';
        document.getElementById('fb-root').appendChild(e);
      }());
    </script>
  </body>
</html>

Now depending on your application, you may want to use subscribe to the auth.authResponseChange event to always insure you "know" the latest state of the current user (still logged-in...etc):

FB.Event.subscribe('auth.authResponseChange', function(response) {
    window.location.reload();
});

Or you may choose to check whenever you require an action from the user and in this case you would use the FB.getLoginStatus() method:

function call_to_action() {
    FB.getLoginStatus(function(response) {
        if (response.authResponse) {
            // logged in and connected user, someone you know

            // proceed with your flow
        } else {
            // no user session available, someone you dont know

            // trigger FB.login() ...etc
        }
    });
}

Now you always place members related content within if($user) statement:

<?php if($user) { ?>
    <p>s3cr3t data</p>
<?php } else { ?>
    <p>Please login!</p>
<?php } ?>
Comments