AHMAD ASJAD – احمد اسجد

Developer

  • HOME
  • Question & Answer
  • CONTACT

Monthly Archives: November 2016

November 9, 2016

Login with Facebook

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

Code Block   
  1. <a class="btn btn-block btn-social btn-facebook" onClick="logInWithFacebook()">
  2. <span class="fa fa-facebook"></span>
  3. Login with Facebook
  4. </a>

Step 4:

Now play with js to tackle the response of the facebook

Code Block   
  1. <script>
  2. logInWithFacebook = function () {
  3. FB.login(function (response) {
  4. if (response.authResponse) {
  5. // Now you can redirect the user or do an AJAX request to
  6. // a PHP script that grabs the signed request from the cookie.
  7. jQuery.ajax({
  8. url: 'fb-js-login.php',
  9. type: 'get',
  10. success: function (data) {
  11. if (data == 'correct') {
  12. location.reload();
  13. } else {
  14. jQuery('.login-message').html(data);
  15. console.log(data);
  16. }
  17. },
  18. error: function (xhr, status, errorThrown) {
  19. console.log(xhr);
  20. }
  21. });
  22.  
  23. } else {
  24. alert('User cancelled login or did not fully authorize.');
  25. }
  26. }, {scope: 'email'});
  27. return false;
  28. };
  29. window.fbAsyncInit = function () {
  30. FB.init({
  31. appId: 'your_app_id_goes_here',
  32. cookie: true, // This is important, it's not enabled by default
  33. version: 'v2.2'
  34. });
  35. };
  36.  
  37. (function (d, s, id) {
  38. var js, fjs = d.getElementsByTagName(s)[0];
  39. if (d.getElementById(id)) {
  40. return;
  41. }
  42. js = d.createElement(s);
  43. js.id = id;
  44. js.src = "//connect.facebook.net/en_US/sdk.js";
  45. fjs.parentNode.insertBefore(js, fjs);
  46. }(document, 'script', 'facebook-jssdk'));
  47. </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

 

Code Block   
  1. CREATE TABLE `tbl_user` (
  2. `id` int(11) NOT NULL,
  3. `first_name` varchar(255) NOT NULL,
  4. `last_name` varchar(255) NOT NULL,
  5. `email` varchar(255) NOT NULL,
  6. `mobile` varchar(255) NOT NULL,
  7. `address` longtext NOT NULL,
  8. `area` varchar(500) NOT NULL,
  9. `city` varchar(255) NOT NULL,
  10. `state` varchar(255) NOT NULL,
  11. `country` varchar(255) NOT NULL,
  12. `password` varchar(255) NOT NULL,
  13. `confirm` varchar(255) NOT NULL,
  14. `photo` varchar(256) NOT NULL,
  15. `created_at` date NOT NULL,
  16. `status` enum('active','inactive') NOT NULL DEFAULT 'inactive',
  17. `auth_key` text
  18. ) ENGINE=InnoDB DEFAULT CHARSET=latin1;
  19.  
  20.  
  21. ALTER TABLE `register`
  22. ADD PRIMARY KEY (`id`);

 

 

Step 6:

Now authenticate facebook data with your database table. If it’s available, then log him/her in.

Code Block   
  1. <?php include 'include/conn.php'; ?>
  2. <?php
  3.  
  4. include_once dirname(__FILE__). '/facebook/graph-sdk/src/Facebook/autoload.php';
  5.  
  6. //js-login.php
  7. $fb = new Facebook\Facebook([
  8. 'app_id' => 'Your_app_id_goes_here',
  9. 'app_secret' => 'your_app_secret_goes_here',
  10. 'default_graph_version' => 'v2.2',
  11. ]);
  12.  
  13. $helper = $fb->getJavaScriptHelper();
  14.  
  15. try {
  16. $accessToken = $helper->getAccessToken();
  17. } catch (Facebook\Exceptions\FacebookResponseException $e) {
  18. // When Graph returns an error
  19. echo 'Graph returned an error: ' . $e->getMessage();
  20. exit;
  21. } catch (Facebook\Exceptions\FacebookSDKException $e) {
  22. // When validation fails or other local issues
  23. echo 'Facebook SDK returned an error: ' . $e->getMessage();
  24. exit;
  25. }
  26.  
  27. if (!isset($accessToken)) {
  28. echo 'No cookie set or no OAuth data could be obtained from cookie.';
  29. exit;
  30. }
  31.  
  32. // Logged in
  33. $_SESSION['fb_access_token'] = (string) $accessToken;
  34.  
  35. try {
  36. // Returns a `Facebook\FacebookResponse` object
  37. $response = $fb->get('/me?fields=id,name,email', $_SESSION['fb_access_token']);
  38. } catch (Facebook\Exceptions\FacebookResponseException $e) {
  39. echo 'Graph returned an error: ' . $e->getMessage();
  40. exit;
  41. } catch (Facebook\Exceptions\FacebookSDKException $e) {
  42. echo 'Facebook SDK returned an error: ' . $e->getMessage();
  43. exit;
  44. }
  45. //All information received from facebook is stored in $user variable
  46. $user = $response->getGraphUser();
  47.  
  48. $email = $user ['email'];
  49. $que = "select * from register where email='$email' AND status='active'";
  50. $run = mysql_query($que);
  51. $count = mysql_num_rows($run);
  52. if ($count > 0) {
  53. $rst = mysql_fetch_assoc($run);
  54. $_SESSION ['user_email'] = $email;
  55. $_SESSION ['userfname'] = $rst ['fname'];
  56. $_SESSION ['userlogin_id'] = $rst ['id'];
  57. } else {
  58. //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
  59. echo "Your are not registered with this website";
  60. }

 

download the complete code: login-with-facebook-example

Posted in PHP, Programming by ahmadasjad Leave a comment

Categories

  • Algorithm (10)
  • Array (2)
  • Database (5)
    • MySQL (5)
    • SQL (1)
  • Design Pattern (1)
  • e-Commerce (1)
    • Magento (1)
  • Framework (3)
    • Yii Framework (3)
  • Function (14)
  • HTML (1)
  • JavaScript (4)
  • JQuery (5)
  • Method (6)
  • OS (2)
    • Ubuntu (1)
    • Windows (1)
  • PHP (25)
  • Programming (30)
    • Python (1)
  • Server (1)
  • Sorting (1)
  • Uncategorized (1)
  • XAMPP (1)

Old Post

  • October 2018 (2)
  • February 2018 (2)
  • November 2017 (1)
  • February 2017 (1)
  • December 2016 (2)
  • November 2016 (1)
  • August 2016 (3)
  • July 2016 (1)
  • June 2016 (1)
  • May 2016 (1)
  • April 2016 (2)
  • January 2016 (3)
  • December 2015 (5)
  • November 2015 (7)
  • May 2015 (1)
  • March 2015 (2)
  • January 2015 (2)
  • December 2014 (1)
  • February 2014 (1)
This Site is owned by Ahmad Asjad & All © Reserved to him
ahmadasjad.in
 

Loading Comments...