<? Online-PHP::Tutorials ?>

« Back

  • Integrate facebook login to website

    The source code looks like:

    <?php

    define('YOUR_APP_ID', 'your app id ');
    define('YOUR_APP_SECRET', 'your app secret');

    function get_facebook_cookie($app_id, $app_secret) {
      $args = array();
      parse_str(trim($_COOKIE['fbs_' . $app_id], '\\"'), $args);
      ksort($args);
      $payload = '';
      foreach ($args as $key => $value) {
        if ($key != 'sig') {
          $payload .= $key . '=' . $value;
        }
      }
      if (md5($payload . $app_secret) != $args['sig']) {
        return null;
      }
      return $args;
    }

    $cookie = get_facebook_cookie(YOUR_APP_ID, YOUR_APP_SECRET);

    $user = json_decode(file_get_contents(
        'https://graph.facebook.com/me?access_token=' .
        $cookie['access_token']));

    ?>

    <div id="fb-root"></div>
    <script>
    window.fbAsyncInit = function() {
        FB.init({appId: 'YOUR_APP_ID', status: true, cookie: true, xfbml: true});
     
        FB.Event.subscribe('auth.login', function(response) {

           login();
        });
        FB.Event.subscribe('auth.logout', function(response) {
           logout();
        });
        FB.getLoginStatus(function(response) {
           if (response.session) {
             greet();
           }
        });    
          
        function login() {
           FB.api('/me', function(response) {
      alert('You have successfully logged in, '+response.name+"!");
           });
        }
        function logout() {
           alert('You have successfully logged out!');
        }
        function greet() {
           FB.api('/me', function(response) {
             alert('Welcome, '+response.name+"!");
           });
        }    
    };
    (function() {
       var e = document.createElement('script');
       e.type = 'text/javascript';
       e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
       e.async = true;
       document.getElementById('fb-root').appendChild(e);
    }());
    </script>
    <fb:login-button autologoutlink='true'  perms='email,user_birthday,status_update,publish_stream'></fb:login-button>
     
     
    Ofcourse make sure you change the YOUR_APP_ID and YOUR_APP_SECRET with your facebook app data.
     
    Enjoy