How To Add Facebook Login to PHP Website

 How To Add Facebook Login to PHP Website

Long registration forms that are a huge hassle to fill and a real pain to validate are now a thing of the past. These days, developers have worked around this thorny UX issue by using Facebook Login for their applications.


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:

  1. Create a Facebook application.
  2. Create an application on the server.
  3. Download Facebook SDK.
  4. 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.

create app

Click Add New App button and select Website as the platform.

select 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.

add facebook app

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.

add new domain

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.

cloudways application management

Go to the application folder by running the following command

  1. $ 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.

  1. {
  2. "require" : {
  3. "facebook/graph-sdk" : "~5.0"
  4. }
  5. }

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.

  1. <?php
  2. //initialize facebook sdk
  3. require 'vendor/autoload.php';
  4. session_start();
  5. $fb = new Facebook\Facebook([
  6. 'app_id' => '1214799411888113',
  7. 'app_secret' => '286f08b36691768f859a70e788f4ceda',
  8. 'default_graph_version' => 'v2.5',
  9. ]);
  10. $helper = $fb->getRedirectLoginHelper();
  11. $permissions = ['email']; // optional
  12. try {
  13. if (isset($_SESSION['facebook_access_token'])) {
  14. $accessToken = $_SESSION['facebook_access_token'];
  15. } else {
  16. $accessToken = $helper->getAccessToken();
  17. }
  18. } catch(Facebook\Exceptions\facebookResponseException $e) {
  19. // When Graph returns an error
  20. echo 'Graph returned an error: ' . $e->getMessage();
  21. exit;
  22. } catch(Facebook\Exceptions\FacebookSDKException $e) {
  23. // When validation fails or other local issues
  24. echo 'Facebook SDK returned an error: ' . $e->getMessage();
  25. exit;
  26. }
  27. if (isset($accessToken)) {
  28. if (isset($_SESSION['facebook_access_token'])) {
  29. $fb->setDefaultAccessToken($_SESSION['facebook_access_token']);
  30. } else {
  31. // getting short-lived access token
  32. $_SESSION['facebook_access_token'] = (string) $accessToken;
  33. // OAuth 2.0 client handler
  34. $oAuth2Client = $fb->getOAuth2Client();
  35. // Exchanges a short-lived access token for a long-lived one
  36. $longLivedAccessToken = $oAuth2Client->getLongLivedAccessToken($_SESSION['facebook_access_token']);
  37. $_SESSION['facebook_access_token'] = (string) $longLivedAccessToken;
  38. // setting default access token to be used in script
  39. $fb->setDefaultAccessToken($_SESSION['facebook_access_token']);
  40. }
  41. // redirect the user to the profile page if it has "code" GET variable
  42. if (isset($_GET['code'])) {
  43. header('Location: profile.php');
  44. }
  45. // getting basic info about user
  46. try {
  47. $profile_request = $fb->get('/me?fields=name,first_name,last_name,email');
  48. $requestPicture = $fb->get('/me/picture?redirect=false&height=200'); //getting user picture
  49. $picture = $requestPicture->getGraphUser();
  50. $profile = $profile_request->getGraphUser();
  51. $fbid = $profile->getProperty('id'); // To Get Facebook ID
  52. $fbfullname = $profile->getProperty('name'); // To Get Facebook full name
  53. $fbemail = $profile->getProperty('email'); // To Get Facebook email
  54. $fbpic = "<img src='".$picture['url']."' class='img-rounded'/>";
  55. # save the user nformation in session variable
  56. $_SESSION['fb_id'] = $fbid.'</br>';
  57. $_SESSION['fb_name'] = $fbfullname.'</br>';
  58. $_SESSION['fb_email'] = $fbemail.'</br>';
  59. $_SESSION['fb_pic'] = $fbpic.'</br>';
  60. } catch(Facebook\Exceptions\FacebookResponseException $e) {
  61. // When Graph returns an error
  62. echo 'Graph returned an error: ' . $e->getMessage();
  63. session_destroy();
  64. // redirecting user back to app login page
  65. header("Location: ./");
  66. exit;
  67. } catch(Facebook\Exceptions\FacebookSDKException $e) {
  68. // When validation fails or other local issues
  69. echo 'Facebook SDK returned an error: ' . $e->getMessage();
  70. exit;
  71. }
  72. } else {
  73. // 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
  74. $loginUrl = $helper->getLoginUrl('https://phpstack-21306-56790-161818.cloudwaysapps.com', $permissions);
  75. echo '<a href="' . $loginUrl . '">Log in with Facebook!</a>';
  76. }
  77. ?>

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.

  1. <?php
  2. session_start();
  3. ?>
  4. <head>
  5. <title>Login with Facebook</title>
  6. <link href = "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel = "stylesheet">
  7. </head>
  8. <body>
  9. <?php if($_SESSION['fb_id']) {?>
  10. <div class = "container">
  11. <div class = "jumbotron">
  12. <h1>Hello <?php echo $_SESSION['fb_name']; ?></h1>
  13. <p>Welcome to Cloudways</p>
  14. </div>
  15. <ul class = "nav nav-list">
  16. <h4>Image</h4>
  17. <li><?php echo $_SESSION['fb_pic']?></li>
  18. <h4>Facebook ID</h4>
  19. <li><?php echo $_SESSION['fb_id']; ?></li>
  20. <h4>Facebook fullname</h4>
  21. <li><?php echo $_SESSION['fb_name']; ?></li>
  22. <h4>Facebook Email</h4>
  23. <li><?php echo $_SESSION['fb_email']; ?></li>
  24. </ul>
  25. </div>
  26. <?php } ?>
  27. </body>
  28. </html>

As you can see, the information is presented in a very simple format.

Q: Why use Facebook Login in PHP websites?

A: Using Facebook login in your PHP website helps your visitors to login directly from their Facebook accounts. It allows them to share articles, add comments etc. directly from their Facebook profiles.

Q: What library to use for Facebook login in PHP?

A: You can use Facebook SDK which is a powerful PHP library built with advanced features for integrating Facebook Login in PHP websites.

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.

Share This Article

Comments