How To Add Facebook Login to PHP Website
Facebook offers an excellent alternate to the traditional form based login process that has long been a part of the PHP applications. The idea is very simple; you just have to put a Facebook button on the registration page. Next, save the user data after successful login. In this article, I will explain how you can add Facebook Login to PHP apps and get the users’ data.
The process has four steps:
- Create a Facebook application.
- Create an application on the server.
- Download Facebook SDK.
- Initialize SDK and get user information.
Create an Application in Facebook
To implement Facebook Login system for the application, the first step is the creation of an app through the Facebook account.
Sign into the Facebook and go to developer.Facebook.com .
Once there, create an app.
Click Add New App button and select Website as the platform.
Host Your PHP Apps With Us For 10x Faster Performance
Don’t Let Your Customers Run Away With The Downtimes. Deploy With Us Today!
Enter the app’s name, an email id and select a category for the application. Now click Create App Id button. This will create an app in Facebook.
Now go to Settings, where the App Secret and App ID could be found. These ids will be used in the PHP application. Remember to add the website’s URL in App Domains.
Down the page, Click the Add Platform tab. Add website as a platform and enter the URL of the
website again.
This finishes the creation of the Facebook App. The next step is to create a server on a fast and reliable hosting platform.
Create an Application on Server
Visit the server and launch the SSH terminal. Login to SSH by using the master credentials.
Go to the application folder by running the following command
- $ cd applications/{your application folder}/private_html/
Download Facebook SDK
Composer is the recommended method of installing libraries on the platform and I will use it to install Facebook SDK.The first step is the creation of a composer file. In the SSH terminal run composer init command and add the required information to it. It will create a composer.json file in the application folder. Add the following code in composer.json.
- {
- "require" : {
- "facebook/graph-sdk" : "~5.0"
- }
- }
Now run composer install command in SSH to finalize installation of Facebook SDK.
Initialize SDK and Get User Information
It is now time to initialize Facebook SDK and get access_token from Facebook. After authenticating the token, the user info will be fetched and the view will be redirected to the profile page that shows the user information.
Create two files in the application folder; Index.php and Profile.php.
Add the following code to index.php file. Comments are added to explain the code.
- <?php
- //initialize facebook sdk
- require 'vendor/autoload.php';
- session_start();
- $fb = new Facebook\Facebook([
- 'app_id' => '1214799411888113',
- 'app_secret' => '286f08b36691768f859a70e788f4ceda',
- 'default_graph_version' => 'v2.5',
- ]);
- $helper = $fb->getRedirectLoginHelper();
- $permissions = ['email']; // optional
- try {
- if (isset($_SESSION['facebook_access_token'])) {
- $accessToken = $_SESSION['facebook_access_token'];
- } else {
- $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)) {
- if (isset($_SESSION['facebook_access_token'])) {
- $fb->setDefaultAccessToken($_SESSION['facebook_access_token']);
- } else {
- // getting short-lived access token
- $_SESSION['facebook_access_token'] = (string) $accessToken;
- // OAuth 2.0 client handler
- $oAuth2Client = $fb->getOAuth2Client();
- // Exchanges a short-lived access token for a long-lived one
- $longLivedAccessToken = $oAuth2Client->getLongLivedAccessToken($_SESSION['facebook_access_token']);
- $_SESSION['facebook_access_token'] = (string) $longLivedAccessToken;
- // setting default access token to be used in script
- $fb->setDefaultAccessToken($_SESSION['facebook_access_token']);
- }
- // redirect the user to the profile page if it has "code" GET variable
- if (isset($_GET['code'])) {
- header('Location: profile.php');
- }
- // getting basic info about user
- try {
- $profile_request = $fb->get('/me?fields=name,first_name,last_name,email');
- $requestPicture = $fb->get('/me/picture?redirect=false&height=200'); //getting user picture
- $picture = $requestPicture->getGraphUser();
- $profile = $profile_request->getGraphUser();
- $fbid = $profile->getProperty('id'); // To Get Facebook ID
- $fbfullname = $profile->getProperty('name'); // To Get Facebook full name
- $fbemail = $profile->getProperty('email'); // To Get Facebook email
- $fbpic = "<img src='".$picture['url']."' class='img-rounded'/>";
- # save the user nformation in session variable
- $_SESSION['fb_id'] = $fbid.'</br>';
- $_SESSION['fb_name'] = $fbfullname.'</br>';
- $_SESSION['fb_email'] = $fbemail.'</br>';
- $_SESSION['fb_pic'] = $fbpic.'</br>';
- } catch(Facebook\Exceptions\FacebookResponseException $e) {
- // When Graph returns an error
- echo 'Graph returned an error: ' . $e->getMessage();
- session_destroy();
- // redirecting user back to app login page
- header("Location: ./");
- exit;
- } catch(Facebook\Exceptions\FacebookSDKException $e) {
- // When validation fails or other local issues
- echo 'Facebook SDK returned an error: ' . $e->getMessage();
- exit;
- }
- } else {
- // replace your website URL same as added in the developers.Facebook.com/apps e.g. if you used http instead of https and you used
- $loginUrl = $helper->getLoginUrl('https://phpstack-21306-56790-161818.cloudwaysapps.com', $permissions);
- echo '<a href="' . $loginUrl . '">Log in with Facebook!</a>';
- }
- ?>
Once done, go to the application URL in browser. You will see the Facebook button for login. Click it and the page will redirect to Facebook login page. Sign into the Facebook account. After successful login, the page will be redirected to the profile page.
Add the following code to profile.php to show the retrieved information. For the purpose of this tutorial, I will retrieve user id, Facebook profile picture, name and email.
- <?php
- session_start();
- ?>
- <head>
- <title>Login with Facebook</title>
- <link href = "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel = "stylesheet">
- </head>
- <body>
- <?php if($_SESSION['fb_id']) {?>
- <div class = "container">
- <div class = "jumbotron">
- <h1>Hello <?php echo $_SESSION['fb_name']; ?></h1>
- <p>Welcome to Cloudways</p>
- </div>
- <ul class = "nav nav-list">
- <h4>Image</h4>
- <li><?php echo $_SESSION['fb_pic']?></li>
- <h4>Facebook ID</h4>
- <li><?php echo $_SESSION['fb_id']; ?></li>
- <h4>Facebook fullname</h4>
- <li><?php echo $_SESSION['fb_name']; ?></li>
- <h4>Facebook Email</h4>
- <li><?php echo $_SESSION['fb_email']; ?></li>
- </ul>
- </div>
- <?php } ?>
- </body>
- </html>
As you can see, the information is presented in a very simple format.
Conclusion
In this tutorial, I demonstrated how to integrate Facebook Login button in your PHP apps. This will do away with the hassles of filling in and parsing long registration forms. If you need to ask a question about the code or wish to add to the conversation, please leave a comment below.
Comments
Post a Comment