Filip Glazar Filip Glazar - 2 months ago 12x
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.


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


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="">
    <?php if ($user) { ?>
      Your user profile is
        <?php print htmlspecialchars(print_r($user_profile, true)) ?>
    <?php } else { ?>
    <?php } ?>
    <div id="fb-root"></div>
      window.fbAsyncInit = function() {
          appId: '<?php echo $facebook->getAppID() ?>',
          cookie: true,
          xfbml: true,
          oauth: true
        FB.Event.subscribe('auth.login', function(response) {
        FB.Event.subscribe('auth.logout', function(response) {
      (function() {
        var e = document.createElement('script'); e.async = true;
        e.src = document.location.protocol +

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

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