Home PHP Log in with Facebook using PHP

Log in with Facebook using PHP

Author

Date

Category

To allow users to log in with Facebook using PHP, you will need to use the Facebook PHP SDK. Here are the basic steps:

  1. Create a new Facebook app in the Facebook developer console and get the App ID and App Secret.
  2. Install the Facebook PHP SDK in your project using Composer or download it from GitHub.
  3. Include the Facebook PHP SDK in your PHP script by requiring the autoload.php file:
require_once 'path/to/autoload.php';
PHP
  1. Initialize the Facebook PHP SDK with your App ID and App Secret:
$fb = new \Facebook\Facebook([
  'app_id' => '{your-app-id}',
  'app_secret' => '{your-app-secret}',
  'default_graph_version' => 'v3.2',
]);
PHP
  1. Create a Facebook login button on your webpage and link it to the Facebook login page:
<a href="<?php echo $fb->getRedirectLoginHelper()->getLoginUrl('{redirect-url}', ['email']); ?>">Log in with Facebook</a>
PHP
  1. When the user clicks the login button, they will be redirected to the Facebook login page. After the user logs in and grants permission to your app, Facebook will redirect them back to the specified redirect URL. You can handle the login callback in your PHP script:
$helper = $fb->getRedirectLoginHelper();

try {
  $accessToken = $helper->getAccessToken();
} catch(\Facebook\Exceptions\FacebookResponseException $e) {
  // When Graph returns an error
  echo 'Graph returned an error: ' . $e->getMessage();
  exit;
} catch(\Facebook\Exceptions\FacebookSDKException $e) {
  // When validation fails or other local issues
  echo 'Facebook SDK returned an error: ' . $e->getMessage();
  exit;
}

if (! isset($accessToken)) {
  echo 'No cookie set or no OAuth data could be obtained from cookie.';
  exit;
}

// Logged in
echo '<h3>Access Token</h3>';
var_dump($accessToken->getValue());

// The OAuth 2.0 client handler helps us manage access tokens
$oAuth2Client = $fb->getOAuth2Client();

// Get the access token metadata from /debug_token
$tokenMetadata = $oAuth2Client->debugToken($accessToken);

echo '<h3>Metadata</h3>';
var_dump($tokenMetadata);
PHP

This code will retrieve the access token and metadata for the logged-in user. From here, you can use the access token to make API requests on behalf of the user.

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Subhash Shipu

PHP Expert

Hey there! I'm a PHP geek on a mission to blog my way through the coding chaos. When I'm not chasing semicolons, I'm busy cuddling my pet Coco, who thinks debugging means chasing her own tail. Join the fun!

Subscribe

Recent posts