Steps to login with facebook using php
In todays day to day life, no one live without using the social websites. This habits of the people makes impact on other websites too. So, getting user information with authentication of social login an easy task for the website user. One of the most popular login with facebook is a very imprtant tool for websites. Follow these steps to successfully integrate login with facebook using php.
Step 1:
Go facebook developer console to create an app and get its secret
Step 2:
Download Facebook PHP SDK
Step 3:
Add this html code whenever you want to show login with facebook button
- <a class="btn btn-block btn-social btn-facebook" onClick="logInWithFacebook()">
- <span class="fa fa-facebook"></span>
- Login with Facebook
- </a>
Step 4:
Now play with js to tackle the response of the facebook
- <script>
- logInWithFacebook = function () {
- FB.login(function (response) {
- if (response.authResponse) {
- // Now you can redirect the user or do an AJAX request to
- // a PHP script that grabs the signed request from the cookie.
- jQuery.ajax({
- url: 'fb-js-login.php',
- type: 'get',
- success: function (data) {
- if (data == 'correct') {
- location.reload();
- } else {
- jQuery('.login-message').html(data);
- console.log(data);
- }
- },
- error: function (xhr, status, errorThrown) {
- console.log(xhr);
- }
- });
-
- } else {
- alert('User cancelled login or did not fully authorize.');
- }
- }, {scope: 'email'});
- return false;
- };
- window.fbAsyncInit = function () {
- FB.init({
- appId: 'your_app_id_goes_here',
- cookie: true, // This is important, it's not enabled by default
- version: 'v2.2'
- });
- };
-
- (function (d, s, id) {
- var js, fjs = d.getElementsByTagName(s)[0];
- if (d.getElementById(id)) {
- return;
- }
- js = d.createElement(s);
- js.id = id;
- js.src = "//connect.facebook.net/en_US/sdk.js";
- fjs.parentNode.insertBefore(js, fjs);
- }(document, 'script', 'facebook-jssdk'));
- </script>
You have completed the part of front end.
Step 5:
if you don’t have a user table in your database, create one something like this
- CREATE TABLE `tbl_user` (
- `id` int(11) NOT NULL,
- `first_name` varchar(255) NOT NULL,
- `last_name` varchar(255) NOT NULL,
- `email` varchar(255) NOT NULL,
- `mobile` varchar(255) NOT NULL,
- `address` longtext NOT NULL,
- `area` varchar(500) NOT NULL,
- `city` varchar(255) NOT NULL,
- `state` varchar(255) NOT NULL,
- `country` varchar(255) NOT NULL,
- `password` varchar(255) NOT NULL,
- `confirm` varchar(255) NOT NULL,
- `photo` varchar(256) NOT NULL,
- `created_at` date NOT NULL,
- `status` enum('active','inactive') NOT NULL DEFAULT 'inactive',
- `auth_key` text
- ) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-
-
- ALTER TABLE `register`
- ADD PRIMARY KEY (`id`);
Step 6:
Now authenticate facebook data with your database table. If it’s available, then log him/her in.
- <?php include 'include/conn.php'; ?>
- <?php
-
-
- //js-login.php
- $fb = new Facebook\Facebook([
- 'app_id' => 'Your_app_id_goes_here',
- 'app_secret' => 'your_app_secret_goes_here',
- 'default_graph_version' => 'v2.2',
- ]);
-
- $helper = $fb->getJavaScriptHelper();
-
- 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;
- }
-
- echo 'No cookie set or no OAuth data could be obtained from cookie.';
- exit;
- }
-
- // Logged in
- $_SESSION['fb_access_token'] = (string) $accessToken;
-
- try {
- // Returns a `Facebook\FacebookResponse` object
- $response = $fb->get('/me?fields=id,name,email', $_SESSION['fb_access_token']);
- } catch (Facebook\Exceptions\FacebookResponseException $e) {
- echo 'Graph returned an error: ' . $e->getMessage();
- exit;
- } catch (Facebook\Exceptions\FacebookSDKException $e) {
- echo 'Facebook SDK returned an error: ' . $e->getMessage();
- exit;
- }
- //All information received from facebook is stored in $user variable
- $user = $response->getGraphUser();
-
- $email = $user ['email'];
- $que = "select * from register where email='$email' AND status='active'";
- if ($count > 0) {
- $_SESSION ['user_email'] = $email;
- $_SESSION ['userfname'] = $rst ['fname'];
- $_SESSION ['userlogin_id'] = $rst ['id'];
- } else {
- //You also can register the user if he is not a user of your website from the information provided by facebook or simply show a message
- echo "Your are not registered with this website";
- }
download the complete code: login-with-facebook-example