Login Facebook with PHP
Facebook Login makes it easy to connect with users on your app or website. You can use several methods in the PHP, JavaScript or mobile SDKs to speed up the registration process and build a functional system in minutes.
In this post I'll show you how to use facebook login PHP SDK

1. Create you facebook app id:
- Go to page: https://developers.facebook.com/apps
- Choose Create New App:
- Remember your App ID and App Secret:
- Change Website with Facebook Login (This link use to redirect back your login page)

2. Download SDK:
You can download the Facebook SDK for PHP from GitHub.

3. Code explain:
- Define App ID and App secret:
// Require SDK
require 'facebook-php-sdk/src/facebook.php';

define('YOUR_APP_ID', 'xxxxxxxxxxx');
define('YOUR_APP_SECRET', 'xxxxxxxxxxx');

$facebook = new Facebook(array(
  'appId'  => 'YOUR_APP_ID',
  'secret' => 'YOUR_APP_SECRET',
));

// Get User ID
$user = $facebook->getUser();
- Get user
if ($user) {
  try {
    // Proceed knowing you have a logged in user who's authenticated.
    $user_profile = $facebook->api('/me');
  } catch (FacebookApiException $e) {
    error_log($e);
    $user = null;
  }
}
- Get Login, Logout URL:
if ($user) {
  $logoutUrl = $facebook->getLogoutUrl();
} else {
  $loginUrl = $facebook->getLoginUrl();
}
- To set the scope and display for login.

  • 'scope' => 'read_stream, email' this code to get public user info and user email
  • 'display'=> 'popup' use to display new window like popup style (Note: you need create a javascript popup window $loginUrl link)

$params = array(
 'scope' => 'read_stream, email',
 'display'=> 'popup'
);
  $loginUrl = $facebook->getLoginUrl($params);
- Javascript popup window use window.open() function.
- Check use and make new user session in php
if(isset($logoutUrl)) 
{
 // Do something like: check user exit, insert user to DB...

 // Create new Session
 $avatar = 'https://graph.facebook.com/'.$user_profile['id'].'/picture?type=large';
 $user = array( 'id'   => $user_profile['id'],
       'email'  => $user_profile['email'],
       'name'  => $user_profile['name'],
       'avatar'  => $avatar,
     );
 // Create new Session
 $_SESSION['ss_user'] = array( 'type'    => 'facebook',
          'user'   => $user
        );
}
else {
 // Create new Session
 header('Location: '. $loginUrl);
}

Done and Enjoy!