This project demonstrates how to implement Facebook Login using PHP SDK. Users can log in using their Facebook account instead of filling long registration forms.
- Login with Facebook account
- Fetch user profile data
- Session-based authentication
- Logout functionality
index.php
welcome.php
fb-callback.php
fb-config.php
logout.php
- Go to Facebook Developers
- Create a new app
- Add Facebook Login product
- Go to Settings → Basic
- Copy App ID
- Copy App Secret
- Go to Facebook Login → Settings
- Add Callback URL
Example:http://localhost/fb-callback.php
- Add Callback URL
- Enable:
- Client OAuth Login
- Web OAuth Login
- Set app status to Live
<?php
session_start();
require_once 'php-graph-sdk-5.x/src/Facebook/autoload.php';
$fb = new Facebook\Facebook([
'app_id' => 'YOUR_APP_ID',
'app_secret' => 'YOUR_APP_SECRET',
'default_graph_version' => 'v3.2',
]);
$helper = $fb->getRedirectLoginHelper();
?><?php
include_once('fb-config.php');
$permissions = ['email'];
$loginUrl = $helper->getLoginUrl('http://localhost/fb-callback.php', $permissions);
?>
<a href="<?php echo htmlspecialchars($loginUrl); ?>">
Login with Facebook
</a><?php
include_once('fb-config.php');
try {
$accessToken = $helper->getAccessToken();
} catch(Exception $e) {
echo 'Error: ' . $e->getMessage();
exit;
}
if (!isset($accessToken)) {
echo 'Access token not found!';
exit;
}
$res = $fb->get('/me', $accessToken->getValue());
$user = $res->getDecodedBody();
$_SESSION['fbUserId'] = $user['id'];
$_SESSION['fbUserName'] = $user['name'];
$_SESSION['fbAccessToken'] = $accessToken->getValue();
header('Location: welcome.php');
exit;
?><?php
session_start();
if(!isset($_SESSION['fbUserId'])){
header('Location: index.php');
exit;
}
?>
<h2>Welcome <?php echo $_SESSION['fbUserName']; ?></h2>
<a href="logout.php">Logout</a><?php
session_start();
session_destroy();
header('Location: index.php');
exit;
?>- PHP (7+ recommended)
- Facebook PHP SDK
- Web server (XAMPP / WAMP / LAMP)
- Replace
YOUR_APP_IDandYOUR_APP_SECRET - Use HTTPS in production
- Keep App Secret secure
- Handle errors properly in production
Free to use and modify.