title: facebook auto re-login from cookie php
body: <p>My website uses Facebook connect for login and the session lifetime on my server is 3600.</p>
  
  <p>I'm using <a href="http://developers.facebook.com/docs/authentication/" rel="nofollow">Client-Side Flow</a> (javascript) redirect to login.php, and login.php retrieve cookies (set by javascript) to get access token.</p>
  
  <p>However, if a user is idled over 3600 seconds, the session on my server expires. ($_SESSION['uid'] does not exists.)
  How can my login.php check the user has already logged in Facebook(not my app) or not?</p>
  
  <p>The solution I'm using is to redirect the user to my javascript page, and "onStatus function" would be automatically trigged by facebook.</p>
  
  <p>I'm searching for a solution which can all be done with login.php to automatically relogin my website if he or she has logged in Facebook (without redirecting to javascript page). Is is possible?</p>
  
  <p>javascript:</p>
  
  <pre><code>FB.init({appId: 'MY_APP_ID', status: true, cookie: true, xfbml: true});
  
  FB.getLoginStatus(function(response) {
      onStatus(response);
      FB.Event.subscribe('auth.statusChange', onStatus);
      FB.Event.subscribe('auth.login', reloadPage);
  });
  
  function onStatus(response) {
      if (response.session) {
          window.location.href = '/login?fb';
      }
  }
  
  function reloadPage(response) {
      if (response.session) {
          window.location.href = '/login?fb';
      }
  }
  </code></pre>
  
  <p>PHP (for login):</p>
  
  <pre><code>function get_facebook_cookie($app_id, $app_secret) {
    $args = array();
    if(!isset($_COOKIE['fbs_' . $app_id]))
        return false;
    parse_str(trim($_COOKIE['fbs_' . $app_id], '\\"'), $args);
    ksort($args);
    $payload = '';
    foreach ($args as $key =&gt; $value) {
      if ($key != 'sig') {
        $payload .= $key . '=' . $value;
      }
    }
    if (md5($payload . $app_secret) != $args['sig']) {
        return false;
    }
    return $args;
  }
  
  $cookie = get_facebook_cookie(MY_APP_ID, MY_APP_SECRET);
  
  if($cookie){
      if($result = @file_get_contents("https://graph.facebook.com/me/?access_token=".$cookie['access_token'])){
          $result = json_decode($result, true);
          $_SESSION['uid'] = $result['id'];
      }
  </code></pre>