title: Login with Facebook using Facebook SDK for PHP
body: <p>I have problems with making login to my site with Facebook.</p>
  
  <p>I have created login using Facebook SDK by following the tutorial at developers.facebook.com , but it does not work for me.</p>
  
  <p>I have wrote a simple test page to find out, what goes wrong. This is the code:</p>
  
  <pre><code>&lt;!DOCTYPE html&gt;
  &lt;html&gt;
  &lt;head&gt;&lt;/head&gt;
  &lt;body&gt;
  &lt;pre&gt;
  &lt;?php
  
  $app_id         = '446458238729594';
  $app_secret     = '********';
  $redirect_uri   = 'http://mysite.localhost/';
  
  try {
  
      echo( 'Including "facebook.php"...' );
      require './src/facebook.php';
      echo( "done.\n\n" );
  
      echo( 'Starting session...' );
      $result = session_start();
      if( $result ) {
          echo( "done.\n\n" );
          echo( "\n=====&gt;&gt;&gt;&gt;&gt; Session array:\n" . var_export( $_SESSION, true )
                  . "\n\n" );
      } else {
          echo( "fail.\n\n" );
          echo( "\n=====&gt;&gt;&gt;&gt;&gt; Session array:\n" . var_export( $_SESSION, true )
                  . "\n\n" );
      }
  
      echo( "Trying to get counter from the session...\n");
      if( isset( $_SESSION['counter'] ) ) {
          echo( 'Value: ' . $_SESSION['counter'] . "\n" );
          echo( "Increasing to one...\n");
          $_SESSION['counter']++;
          echo( "done.\n" );
          echo( 'Value: ' . $_SESSION['counter'] . "\n\n" );
      } else {
          echo( "fail.\n" );
          echo( "Trying to add a counter and set it's value to 0...\n");
          $_SESSION['counter'] = 0;
          echo( 'Value: ' . $_SESSION['counter'] . "\n" );
          echo( "done.\n\n" );
      }
  
      echo( 'Creating an instance of Facebook class...' );
      $facebook = new Facebook(
          array(
              'appId'     =&gt; $app_id,
              'secret'    =&gt; $app_secret,
          )
      );
      echo( "done.\n\n" );
      echo( "The instance of Facebook class:\n" . str_replace( $app_secret,
              '&gt;&gt;&gt;APP_SECRET&lt;&lt;&lt;', var_export( $facebook, true ) ) . "\n\n" );
  
      echo( "\n=====&gt;&gt;&gt;&gt;&gt; Session array:\n" . var_export( $_SESSION, true )
              . "\n\n" );
  
      echo( 'Trying to get user ID...' );
      $user_id = $facebook-&gt;getUser();
      echo( "done.\n\n" );
      echo( "User ID:\n" . var_export( $user_id, true ) . "\n\n" );
  
      echo( "\n=====&gt;&gt;&gt;&gt;&gt; Session array:\n" . var_export( $_SESSION, true )
              . "\n\n" );
  
      echo( 'Trying to get user profile info...' );
      try {
          $user_profile = $facebook-&gt;api( '/me' );
          echo( "done.\n\n" );
          echo( "User profile info:\n" . var_export( $user_profile, true )
                  . "\n\n" );
      } catch( Exception $exception ) {
          echo( "fail. Probably user is not logged in.\n\n" );
          echo( "Exception:\n--------\n" . str_replace( $app_secret,
                  '&gt;&gt;&gt;APP_SECRET&lt;&lt;&lt;', var_export( $exception, true ) )
                  . "\n--------\n\n" );
          $user_id = null;
          echo( "User ID is now NULL.\n\n" );
      }
  
      echo( "\n=====&gt;&gt;&gt;&gt;&gt; Session array:\n" . var_export( $_SESSION, true )
              . "\n\n" );
  
      if( $user ) {
          echo( 'Seems like user is logged in. Getting logout url...' );
          $url = $facebook-&gt;getLogoutUrl();
          echo( "done.\n\n" );
      } else {
          echo( 'Seems like user is NOT logged in. Getting login url...' );
          $url = $facebook-&gt;getLoginUrl(
              array(
                  'scope'         =&gt; 'read_stream, publish_stream, user_birthday,'
                          . ' user_location, user_work_history, user_hometown,'
                          . ' user_photos',
                  'redirect_uri'  =&gt; $redirect_uri,
              )
          );
          echo( "done.\n\n" );
      }
      echo( 'URL:&lt;br&gt;&lt;/pre&gt;&lt;a href=' . $url ."&gt;Login / Logout&lt;/a&gt;&lt;pre&gt;\n\n" );
  
      echo( "\n=====&gt;&gt;&gt;&gt;&gt; Session array:\n"
              . var_export( $_SESSION, true ) . "\n\n" );
  
      if( $user ) {
          echo( 'Seems like user is still logged in. Trying to get some profile'
                  . ' info...' );
          echo( "\nCreating request...\n" );
          $queries = array(
              array(
                  'method'        =&gt; 'GET',
                  'relative_url'  =&gt; '/' . $user,
              ),
              array(
                  'method'        =&gt; 'GET',
                  'relative_url'  =&gt; '/' . $user . '/home?limit=50',
              ),
              array(
                  'method'        =&gt; 'GET',
                  'relative_url'  =&gt; '/' . $user . '/friends',
              ),
              array(
                  'method'        =&gt; 'GET',
                  'relative_url'  =&gt; '/' . $user . '/photos?limit=6',
              ),
          );
          echo( "Request:\n\n" . var_export( $queries, true ) . "\n\n" );
          echo( "\nEncoding request using JSON format...\n" );
          $queries_encoded = json_encode( $queries );
          echo( "Encoded request:\n\n" . var_export( $queries_encoded, true )
                  . "\n\n" );
          try {
              echo( "\nTrying to get response...\n" );
              $response = $facebook-&gt;api( '?batch=' . $queries_encoded, 'POST' );
              echo( "Response:\n\n" . var_export( $response, true ) . "\n\n" );
              echo( "\nTrying to decode response...\n" );
              echo( "\n" . json_decode( $response[0]['body'], true ) . "\n" );
              echo( "\n" . json_decode( $response[1]['body'], true ) . "\n" );
              echo( "\n" . json_decode( $response[2]['body'], true ) . "\n" );
              echo( "\n" . json_decode( $response[3]['body'], true ) . "\n" );
              echo( "\n\ndone.\n\n" );
          } catch( Exception $exception ) {
              echo( "fail.\n\n" );
              echo( "Exception:\n--------\n\n" . str_replace( $app_secret,
                      '&gt;&gt;&gt;APP_SECRET&lt;&lt;&lt;', var_export( $exception, true ) )
                      . "\n--------\n\n" );
          }
      } else {
          echo( 'Seems like user is still NOT logged in. At now we can\'t do'
                  . ' anything. Try to login using the URL above.' );
      }
  
      echo( "\n\n========\n\nSession array:\n" . var_export( $_SESSION, true )
              . "\n\n" );
  
  } catch( Exception $exception ) {
      echo( "\n\n\nAn exception have been trown:\n--------\n\n" . str_replace(
              $app_secret, '&gt;&gt;&gt;APP_SECRET&lt;&lt;&lt;', var_export( $exception, true ) )
              . "\n--------\n\n" );
      echo( "\n\n========\n\nSession array:\n" . var_export( $_SESSION, true )
              . "\n\n" );
  }
  
  ?&gt;
  &lt;/pre&gt;
  &lt;/body&gt;
  &lt;/html&gt;
  </code></pre>
  
  <p>After the first visit of this page (I am not logged in at Facebook), I get this output:</p>
  
  <pre><code>Including "facebook.php"...done.
  
  Starting session...done.
  
  
  =====&gt;&gt;&gt;&gt;&gt; Session array:
  array (
  )
  
  Trying to get counter from the session...
  fail.
  Trying to add a counter and set it's value to 0...
  Value: 0
  done.
  
  Creating an instance of Facebook class...done.
  
  The instance of Facebook class:
  Facebook::__set_state(array(
     'sharedSessionID' =&gt; NULL,
     'appId' =&gt; '446458238729594',
     'appSecret' =&gt; '&gt;&gt;&gt;APP_SECRET&lt;&lt;&lt;',
     'user' =&gt; NULL,
     'signedRequest' =&gt; NULL,
     'state' =&gt; NULL,
     'accessToken' =&gt; NULL,
     'fileUploadSupport' =&gt; false,
     'trustForwarded' =&gt; false,
  ))
  
  
  =====&gt;&gt;&gt;&gt;&gt; Session array:
  array (
    'counter' =&gt; 0,
  )
  
  Trying to get user ID...done.
  
  User ID:
  0
  
  
  =====&gt;&gt;&gt;&gt;&gt; Session array:
  array (
    'counter' =&gt; 0,
  )
  
  Trying to get user profile info...fail. Probably user is not logged in.
  
  Exception:
  --------
  FacebookApiException::__set_state(array(
     'result' =&gt; 
    array (
      'error_code' =&gt; 7,
      'error' =&gt; 
      array (
        'message' =&gt; 'Failed to connect to 2a03:2880:2050:1f01:face:b00c:0:2: Network is unreachable',
        'type' =&gt; 'CurlException',
      ),
    ),
     'message' =&gt; 'Failed to connect to 2a03:2880:2050:1f01:face:b00c:0:2: Network is unreachable',
     'string' =&gt; '',
     'code' =&gt; 7,
     'file' =&gt; '/srv/www/htdocs/mysite/web/src/base_facebook.php',
     'line' =&gt; 967,
     'trace' =&gt; 
    array (
      0 =&gt; 
      array (
        'file' =&gt; '/srv/www/htdocs/mysite/web/src/base_facebook.php',
        'line' =&gt; 899,
        'function' =&gt; 'makeRequest',
        'class' =&gt; 'BaseFacebook',
        'type' =&gt; '-&gt;',
        'args' =&gt; 
        array (
          0 =&gt; 'https://graph.facebook.com/me',
          1 =&gt; 
          array (
            'method' =&gt; 'GET',
            'access_token' =&gt; '446458238729594|&gt;&gt;&gt;APP_SECRET&lt;&lt;&lt;',
          ),
        ),
      ),
      1 =&gt; 
      array (
        'file' =&gt; '/srv/www/htdocs/mysite/web/src/base_facebook.php',
        'line' =&gt; 866,
        'function' =&gt; '_oauthRequest',
        'class' =&gt; 'BaseFacebook',
        'type' =&gt; '-&gt;',
        'args' =&gt; 
        array (
          0 =&gt; 'https://graph.facebook.com/me',
          1 =&gt; 
          array (
            'method' =&gt; 'GET',
          ),
        ),
      ),
      2 =&gt; 
      array (
        'function' =&gt; '_graph',
        'class' =&gt; 'BaseFacebook',
        'type' =&gt; '-&gt;',
        'args' =&gt; 
        array (
          0 =&gt; '/me',
        ),
      ),
      3 =&gt; 
      array (
        'file' =&gt; '/srv/www/htdocs/mysite/web/src/base_facebook.php',
        'line' =&gt; 644,
        'function' =&gt; 'call_user_func_array',
        'args' =&gt; 
        array (
          0 =&gt; 
          array (
            0 =&gt; 
            Facebook::__set_state(array(
               'sharedSessionID' =&gt; NULL,
               'appId' =&gt; '446458238729594',
               'appSecret' =&gt; '&gt;&gt;&gt;APP_SECRET&lt;&lt;&lt;',
               'user' =&gt; 0,
               'signedRequest' =&gt; NULL,
               'state' =&gt; NULL,
               'accessToken' =&gt; '446458238729594|&gt;&gt;&gt;APP_SECRET&lt;&lt;&lt;',
               'fileUploadSupport' =&gt; false,
               'trustForwarded' =&gt; false,
            )),
            1 =&gt; '_graph',
          ),
          1 =&gt; 
          array (
            0 =&gt; '/me',
          ),
        ),
      ),
      4 =&gt; 
      array (
        'file' =&gt; '/srv/www/htdocs/mysite/web/index.php',
        'line' =&gt; 69,
        'function' =&gt; 'api',
        'class' =&gt; 'BaseFacebook',
        'type' =&gt; '-&gt;',
        'args' =&gt; 
        array (
          0 =&gt; '/me',
        ),
      ),
    ),
     'previous' =&gt; NULL,
  ))
  --------
  
  User ID is now NULL.
  
  
  =====&gt;&gt;&gt;&gt;&gt; Session array:
  array (
    'counter' =&gt; 0,
  )
  
  Seems like user is NOT logged in. Getting login url...done.
  
  URL:
  Login / Logout
  
  
  =====&gt;&gt;&gt;&gt;&gt; Session array:
  array (
    'counter' =&gt; 0,
    'fb_446458238729594_state' =&gt; '84260edcd60940884d261812496a488c',
  )
  
  Seems like user is still NOT logged in. At now we can't do anything. Try to login using the URL above.
  
  ========
  
  Session array:
  array (
    'counter' =&gt; 0,
    'fb_446458238729594_state' =&gt; '84260edcd60940884d261812496a488c',
  )
  </code></pre>
  
  <p>Then I try to login using the given URL. It leads me to my Facebook app authorization page. After confirming the requested permissions, it redirects me to this URL:</p>
  
  <pre><code>http://mysite.localhost/?state=84260edcd60940884d261812496a488c&amp;code=AQDkHPlXXweEiTjXg-sUXwwQAy0_xRYc89Opfz6AF9dlGOomCSG7fjf0440ctHuADKMEG4P7CheeNx9PnwUta-jkfpm03MjDCKyieOZpIPG-evlKYm64mRxD2Q5f_-HJROIC9I_-lHswr5RT3huSQySA55pD28b07Ouv87NqihZ1brGfU-_0LyhcdldtNikb-2xn6NRpa17xEmU37pBqDV1r#_=_
  </code></pre>
  
  <p>After that I expect that I am logged in and my page retrieves and shows me some info from my Facebook profile, but it doesn't. I get this output:</p>
  
  <pre><code>Including "facebook.php"...done.
  
  Starting session...done.
  
  
  =====&gt;&gt;&gt;&gt;&gt; Session array:
  array (
    'counter' =&gt; 0,
    'fb_446458238729594_state' =&gt; '84260edcd60940884d261812496a488c',
  )
  
  Trying to get counter from the session...
  Value: 0
  Increasing to one...
  done.
  Value: 1
  
  Creating an instance of Facebook class...done.
  
  The instance of Facebook class:
  Facebook::__set_state(array(
     'sharedSessionID' =&gt; NULL,
     'appId' =&gt; '446458238729594',
     'appSecret' =&gt; '&gt;&gt;&gt;APP_SECRET&lt;&lt;&lt;',
     'user' =&gt; NULL,
     'signedRequest' =&gt; NULL,
     'state' =&gt; '84260edcd60940884d261812496a488c',
     'accessToken' =&gt; NULL,
     'fileUploadSupport' =&gt; false,
     'trustForwarded' =&gt; false,
  ))
  
  
  =====&gt;&gt;&gt;&gt;&gt; Session array:
  array (
    'counter' =&gt; 1,
    'fb_446458238729594_state' =&gt; '84260edcd60940884d261812496a488c',
  )
  
  Trying to get user ID...done.
  
  User ID:
  0
  
  
  =====&gt;&gt;&gt;&gt;&gt; Session array:
  array (
    'counter' =&gt; 1,
  )
  
  Trying to get user profile info...fail. Probably user is not logged in.
  
  Exception:
  --------
  FacebookApiException::__set_state(array(
     'result' =&gt; 
    array (
      'error_code' =&gt; 7,
      'error' =&gt; 
      array (
        'message' =&gt; 'Failed to connect to 2a03:2880:2050:1f01:face:b00c:0:2: Network is unreachable',
        'type' =&gt; 'CurlException',
      ),
    ),
     'message' =&gt; 'Failed to connect to 2a03:2880:2050:1f01:face:b00c:0:2: Network is unreachable',
     'string' =&gt; '',
     'code' =&gt; 7,
     'file' =&gt; '/srv/www/htdocs/mysite/web/src/base_facebook.php',
     'line' =&gt; 967,
     'trace' =&gt; 
    array (
      0 =&gt; 
      array (
        'file' =&gt; '/srv/www/htdocs/mysite/web/src/base_facebook.php',
        'line' =&gt; 899,
        'function' =&gt; 'makeRequest',
        'class' =&gt; 'BaseFacebook',
        'type' =&gt; '-&gt;',
        'args' =&gt; 
        array (
          0 =&gt; 'https://graph.facebook.com/me',
          1 =&gt; 
          array (
            'method' =&gt; 'GET',
            'access_token' =&gt; '446458238729594|&gt;&gt;&gt;APP_SECRET&lt;&lt;&lt;',
          ),
        ),
      ),
      1 =&gt; 
      array (
        'file' =&gt; '/srv/www/htdocs/mysite/web/src/base_facebook.php',
        'line' =&gt; 866,
        'function' =&gt; '_oauthRequest',
        'class' =&gt; 'BaseFacebook',
        'type' =&gt; '-&gt;',
        'args' =&gt; 
        array (
          0 =&gt; 'https://graph.facebook.com/me',
          1 =&gt; 
          array (
            'method' =&gt; 'GET',
          ),
        ),
      ),
      2 =&gt; 
      array (
        'function' =&gt; '_graph',
        'class' =&gt; 'BaseFacebook',
        'type' =&gt; '-&gt;',
        'args' =&gt; 
        array (
          0 =&gt; '/me',
        ),
      ),
      3 =&gt; 
      array (
        'file' =&gt; '/srv/www/htdocs/mysite/web/src/base_facebook.php',
        'line' =&gt; 644,
        'function' =&gt; 'call_user_func_array',
        'args' =&gt; 
        array (
          0 =&gt; 
          array (
            0 =&gt; 
            Facebook::__set_state(array(
               'sharedSessionID' =&gt; NULL,
               'appId' =&gt; '446458238729594',
               'appSecret' =&gt; '&gt;&gt;&gt;APP_SECRET&lt;&lt;&lt;',
               'user' =&gt; 0,
               'signedRequest' =&gt; NULL,
               'state' =&gt; NULL,
               'accessToken' =&gt; '446458238729594|&gt;&gt;&gt;APP_SECRET&lt;&lt;&lt;',
               'fileUploadSupport' =&gt; false,
               'trustForwarded' =&gt; false,
            )),
            1 =&gt; '_graph',
          ),
          1 =&gt; 
          array (
            0 =&gt; '/me',
          ),
        ),
      ),
      4 =&gt; 
      array (
        'file' =&gt; '/srv/www/htdocs/mysite/web/index.php',
        'line' =&gt; 69,
        'function' =&gt; 'api',
        'class' =&gt; 'BaseFacebook',
        'type' =&gt; '-&gt;',
        'args' =&gt; 
        array (
          0 =&gt; '/me',
        ),
      ),
    ),
     'previous' =&gt; NULL,
  ))
  --------
  
  User ID is now NULL.
  
  
  =====&gt;&gt;&gt;&gt;&gt; Session array:
  array (
    'counter' =&gt; 1,
  )
  
  Seems like user is NOT logged in. Getting login url...done.
  
  URL:
  Login / Logout
  
  
  =====&gt;&gt;&gt;&gt;&gt; Session array:
  array (
    'counter' =&gt; 1,
    'fb_446458238729594_state' =&gt; '6ae5ea9e5f7199fb6d19793905dcdd65',
  )
  
  Seems like user is still NOT logged in. At now we can't do anything. Try to login using the URL above.
  
  ========
  
  Session array:
  array (
    'counter' =&gt; 1,
    'fb_446458238729594_state' =&gt; '6ae5ea9e5f7199fb6d19793905dcdd65',
  )
  </code></pre>
  
  <p>Please, help me figure out, why login does not work? Why the instance of Facebook class does not retrieve the access token? And why the method Facebook::getUser() always returns 0? How can I fix it?</p>