Facebook Login Feature For Your Website

Logging in users for various purposes is now becoming mandatory with the increasing usage of the Internet. Most users may not like to create an account on your website for small purposes. Moreover, filling up your customized signup form and remembering your site’s ID and passwords may seem tedious and uninteresting.

In these situations, users prefer to have a common login credential, which is possible by using third party APIs. Facebook is one of the most used social media along with other services like Gmail, Twitter, Yahoo, etc. Today, in this post we will discuss logging in users with Facebook for your sites.

What you need is to have a Facebook App of yours, which can be generated at developers.facebook.com. For a detailed guide on creating a Facebook app, please visit here. Once, you are done with creating the Facebook application, you can proceed with the following steps.

Facebook Login: Logging in users with Facebook API

Now, we will set up the basic Facebook API for your site. Use the below given code where you need to put your login link.

  1.  <?php
  3. 	error_reporting(E_ALL);
  4. 	ini_set('display_errors','On');
  6. 	// Pass session data over.
  7. 	if(!session_id()) {
  8. 	    session_start();
  9. 	}
  12. 	// Include the required dependencies.
  13. 	require_once( 'inc/facebook/autoload.php' );
  16. 	// Initialize the Facebook PHP SDK v5.
  17. 	$fb = new Facebook\Facebook([
  18. 			'app_id'                => 'xxxxxxxxxxxxxxx',
  19. 			'app_secret'            => 'xxxxxxxxxxxxxxxxxxxxxxxxxxxx',
  20. 			'default_graph_version' => 'v2.3',
  21. 	]);
  24. 	// Choose your app context helper
  25. 	$helper = $fb->getCanvasHelper();
  27. 	$helper = $fb->getRedirectLoginHelper();

In the above code snippet, put in your app_id and app_secret. Now, you need to ask users for various permissions for the data that your FB app can access.

  1. $permissions = ['email', 'user_posts'];

Now, you need to add a callback URL, which has to be the page where you want the user to be redirected after they sign in with Facebook. Also, we will setup the login URL.

  1. $callback = 'http://yoursite.com/index.php';
  2. $loginUrl = $helper->getLoginUrl($callback, $permissions);

Finally, now it is time to make a login URL. You can create the Facebook login URL that matches your sites’ view and feel. Here is the code to make a simple URL.

  1. echo '<a href="' . $loginUrl . '">Log in with Facebook!</a>';