Showing posts with label api. Show all posts
Showing posts with label api. Show all posts

Thursday, February 6, 2020

How to Execute Login With Facebook Account Using PHP

How to Execute  Login With Facebook Account Using PHP

This is another contribution to creating a social login in PHP. In this post we use the Facebook account login to give the user access to our website. Here you can find the registration process for the Facebook PHP SDK library. In this tutorial we used the latest Facebook API SDK library to log in with PHP script.

Most websites usually have the registration form to register and access the website. However, the majority of users are not interested in filling out the registration form for large websites. If you have allowed the user to log in or register with the Facebook login, the user does not currently have to fill out a large registration form and can easily access the website by logging in with a Facebook account. In this blog you will learn how to implement the login with the Facebook account on your PHP website.

Here we used the Facebook PHP SDK library, which you can use to access the Facebook API from your PHP web application. With this library you can easily integrate PHP login with the Facebook account via the Facebook SDK library. Here you can find out how to use Facebook to switch the user login and registration system to PHP and display the user profile data on the website.

Now we have started with the latest version of Facebook SDK v5.x and your system should require the following configuration.


  • The PHP version must be greater than 5.4.
  • The mbstring extension must be activated on your server.



Create Facebook Application


To get access to the Facebook API, you first need to create the Facebook application and then get the application ID and secret App that you can use when calling the Facebook API. Below is a step-by-step guide to creating a Facebook application in the Facebook developer area.



  1. First go to the developer page https://developers.facebook.com/ Facebook and log in with your Facebook account. 


  2. After logging in to Facebook, click the My Applications menu and then click the Create Application link.


  3. After clicking the Create Application link, Modal will appear on the website. Here you need to define the details of the display name of the application and click on the Create Application ID button.



  4. Now navigate to Settings » Base link.


  5. Here you have to enter the domains of the applications, the URL of the privacy policy and the URL of the terms of use and select the category. Finally, you need to click the Save Changes button.


  6. Now you need to navigate to the Add Product page by clicking the plus sign. Then appears modal and here you have to select website.


  7. After selecting the Website option, the Website field on the website is displayed. Here you have to define the URL of your application site.


  8. Now you need to add a product, go to the Link Dashboard and set up the Facebook login product.


  9. After you have configured the Facebook login product, a new website has been loaded. Here you need to define the valid OAuth forwarding URIs and click the Save Changes button.


  10. You have changed your status from development mode to live mode. To do this, you must click the Deactivate button. After clicking the Deactivate button, the modal is displayed. Here you have to select category and click on the Change Mode button. After you click the Change Mode button, your application goes live. This is necessary in order to retrieve profile data from the Facebook API.





Download Facebook SDK for PHP


Then we want to download the Facebook SDK for the PHP library. To do this, we need to open the Command Prompt Editor. In this first step, you need to go to the directory where you want to download the Facebook SDK for PHP. After that, you need to run the Composer command since we used the Composer dependency manager to download the Facebook SDK for PHP. After that, you need to run the following command


composer require facebook/graph-sdk


This command downloads the Facebook SDK library for PHP in the definition directory.


config.php


In this file, we first need to add the autoload.php file from the Facebook SDK library for PHP using the require_once statement.

Then we have to check whether the session variable was started with the PHP function session_id () or not.

Now we need to call the Facebook API, here we need to define the app_id and app_secret key that we need to get when building the Facebook application. Here we also have to define default_graph_version.



<?php

require_once 'vendor/autoload.php';

if (!session_id())
{
    session_start();
}

// Call Facebook API

$facebook = new \Facebook\Facebook([
  'app_id'      => '921130358246916',
  'app_secret'     => '8d382dc63a190925664594ef090b8a78',
  'default_graph_version'  => 'v2.10'
]);

?>


index.php


In this file, we must first add the config.php file with the include statement.

After that we would like help with the redirection of the login. Here we used the getRedirectLoginHelper () method.



Now we want to check whether a variable value $ _GET ['code'] was received or not. If it is received, it means that the user has logged Suppose you got the value of the $ _GET ['code'] variable. Then we would like to check whether the access token was stored in the $ _SESSION variable or not. If it is already stored in the $ _SESSION variable, this value is saved in the local variable.

Assume that the access token is not retrieved from the $ _SESSION variable. Then you have to get it with the getAccessToken () method and save it in the local variable and then in the variable $ _SESSION.

Now that we have received the access token, we want to set the default access token to be used for the request with the setDefaultAccessToken () method.

Now we have retrieved profile data using the get () method and under this method we have to define profile fields like name, email etc. and in the second argument we have to define the value of the access token.


To get user profile data, we used getGraphUser () here. This method creates a graphical collection of users.

In this way we can retrieve data from the Facebook API and save it in the variable $ _SESSION.

To create a link to log in with a Facebook account, we have the getLoginUrl () method here. This method sends the user to log in to Facebook. With this method you have to define the forwarding URL and the authorization matrix.

For this reason, you can call up the source code to log in to Facebook with PHP and display the profile data on the website.



<?php

//index.php

include('config.php');

$facebook_output = '';

$facebook_helper = $facebook->getRedirectLoginHelper();

if(isset($_GET['code']))
{
 if(isset($_SESSION['access_token']))
 {
  $access_token = $_SESSION['access_token'];
 }
 else
 {
  $access_token = $facebook_helper->getAccessToken();

  $_SESSION['access_token'] = $access_token;

  $facebook->setDefaultAccessToken($_SESSION['access_token']);
 }

 $_SESSION['user_id'] = '';
 $_SESSION['user_name'] = '';
 $_SESSION['user_email_address'] = '';
 $_SESSION['user_image'] = '';

 $graph_response = $facebook->get("/me?fields=name,email", $access_token);

 $facebook_user_info = $graph_response->getGraphUser();

 if(!empty($facebook_user_info['id']))
 {
  $_SESSION['user_image'] = 'http://graph.facebook.com/'.$facebook_user_info['id'].'/picture';
 }

 if(!empty($facebook_user_info['name']))
 {
  $_SESSION['user_name'] = $facebook_user_info['name'];
 }

 if(!empty($facebook_user_info['email']))
 {
  $_SESSION['user_email_address'] = $facebook_user_info['email'];
 }
 
}
else
{
 // Get login url
    $facebook_permissions = ['email']; // Optional permissions

    $facebook_login_url = $facebook_helper->getLoginUrl('https://greenhouses-pro.co.uk/demo/', $facebook_permissions);
    
    // Render Facebook login button
    $facebook_login_url = '<div align="center"><a href="'.$facebook_login_url.'"><img src="php-login-with-facebook.gif" /></a></div>';
}



?>
<html>
 <head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <title>How to Execute  Login With Facebook Account Using PHP</title>
  <meta content='width=device-width, initial-scale=1, maximum-scale=1' name='viewport'/>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
  <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
  
 </head>
 <body>
  <div class="container">
   <br />
   <h2 align="center">How to Execute  Login With Facebook Account Using PHP</h2>
   <br />
   <div class="panel panel-default">
    <?php 
    if(isset($facebook_login_url))
    {
     echo $facebook_login_url;
    }
    else
    {
     echo '<div class="panel-heading">Welcome User</div><div class="panel-body">';
     echo '<img src="'.$_SESSION["user_image"].'" class="img-responsive img-circle img-thumbnail" />';
     echo '<h3><b>Name :</b> '.$_SESSION['user_name'].'</h3>';
     echo '<h3><b>Email :</b> '.$_SESSION['user_email_address'].'</h3>';
     echo '<h3><a href="logout.php">Logout</h3></div>';
    }
    ?>
   </div>
  </div>
 </body>
</html>


logout.php



<?php

//logout.php

session_destroy();

header('location:index.php');

?>


In this post, you will learn how to allow the user to log in to the PHP website using a Facebook account. We hope you learn to log in with Facebook in the PHP web application of this publication.

Login with Google Account using PHP

Login with Google Account using PHP

As we know, social networks are a very important part of any web-based application in the Internet world today. If your web application offers functions such as logging into social networks, you will therefore receive more new users for your web application. In this post we have published a tutorial on how to log in, log in or register with the Google account in your PHP web application. Here we create a system in which the user can log in to his website with his Google account.

To sign in with PHP using the Google account, Google has provided the Google OAuth API, which is very simple and useful to implement signing in with the Google account on your website. The Google Sign-In API has given users the right to use their Google Account credentials to log in to the website without registering on that particular website. Using this feature will attract more subscribers to your website. This is because most users currently have a Google account so they can sign in with their Google account without signing in to their website.

This tutorial uses the Google OAuth sign-in API. This API gives users permission to log into their website using their existing Google Accounts. Below you will learn how to integrate the Google login API into your PHP website. You will also learn how to get the API key and integrate the Google client library into your existing PHP library to sign in.

Get Google API Quality


First we need to get the Google API keys, for that you first have a Google account. Therefore, log in to your Google account and follow the steps below.



  1. Go to https://console.developers.google.com/ this link.


  2. Then click the Create New Project link to create a new project.


  3. Enter the name of the project and click the Create button.


  4. Once you have created a new project, you can see your list of projects on the website.


  5. Then click on the Google API logo to go to the homepage.


  6. After you have been redirected to the homepage, select the project in the project selection box.


  7. After clicking on the project selection field, a popup modal is displayed. Below you will find the list of projects. So choose your project.


  8. Now you have to click on the OAuth approval screen in the menu on the left.


  9. As soon as you click on the OAuth consent screen, a page will appear Load, here you have to define the name of the application and then click on the Save button.


  10. If you click the Save button after the page is redirected to another page and click the Create Credentials button here, a drop-down menu will appear and from there you will need to select the OAuth Client ID.


  11. After clicking on the OAuth Client ID menu, you need to redirect to another page. You can find different types of applications here.


  12. Select the web application from another option for the application type. After you select the web application option, a form appears on the web page. Here you need to define the name and URI field for authorized redirection and finally click the Create button.


  13. After clicking the Create button, you can get your client ID and secret client key. You will need to copy both keys to use them in the future to implement login with Google account using PHP. 





Download Google API Client Library for PHP


After receiving the Google API key, we now need to download the Google API Client Library for PHP. To do this, we have to go to the command prompt and first write the Composer command, then we have to run the following command.


composer require google/apiclient:"^2.0"



This command downloads the Google API Client Library for PHP to the definition directory. We have now run the PHP code to use the Google API client library to sign in to the Google account with PHP.


config.php



<?php

//config.php

//Include Google Client Library for PHP autoload file
require_once 'vendor/autoload.php';

//Make object of Google API Client for call Google API
$google_client = new Google_Client();

//Set the OAuth 2.0 Client ID
$google_client->setClientId('1034286712318-kv0gapfqro1aijq84ed72r4aqqs8nan8.apps.googleusercontent.com');

//Set the OAuth 2.0 Client Secret key
$google_client->setClientSecret('Dzq5Xd3olizoZkKjk_SJCWQ1');

//Set the OAuth 2.0 Redirect URI
$google_client->setRedirectUri('http://localhost/tutorial/php-login-using-google-demo/index.php');

//
$google_client->addScope('email');

$google_client->addScope('profile');

//start session on web page
session_start();

?>


index.php



<?php

//index.php

//Include Configuration File
include('config.php');

$login_button = '';

//This $_GET["code"] variable value received after user has login into their Google Account redirct to PHP script then this variable value has been received
if(isset($_GET["code"]))
{
 //It will Attempt to exchange a code for an valid authentication token.
 $token = $google_client->fetchAccessTokenWithAuthCode($_GET["code"]);

 //This condition will check there is any error occur during geting authentication token. If there is no any error occur then it will execute if block of code/
 if(!isset($token['error']))
 {
  //Set the access token used for requests
  $google_client->setAccessToken($token['access_token']);

  //Store "access_token" value in $_SESSION variable for future use.
  $_SESSION['access_token'] = $token['access_token'];

  //Create Object of Google Service OAuth 2 class
  $google_service = new Google_Service_Oauth2($google_client);

  //Get user profile data from google
  $data = $google_service->userinfo->get();

  //Below you can find Get profile data and store into $_SESSION variable
  if(!empty($data['given_name']))
  {
   $_SESSION['user_first_name'] = $data['given_name'];
  }

  if(!empty($data['family_name']))
  {
   $_SESSION['user_last_name'] = $data['family_name'];
  }

  if(!empty($data['email']))
  {
   $_SESSION['user_email_address'] = $data['email'];
  }

  if(!empty($data['gender']))
  {
   $_SESSION['user_gender'] = $data['gender'];
  }

  if(!empty($data['picture']))
  {
   $_SESSION['user_image'] = $data['picture'];
  }
 }
}

//This is for check user has login into system by using Google account, if User not login into system then it will execute if block of code and make code for display Login link for Login using Google account.
if(!isset($_SESSION['access_token']))
{
 //Create a URL to obtain user authorization
 $login_button = '<a href="'.$google_client->createAuthUrl().'"><img src="sign-in-with-google.png" /></a>';
}

?>
<html>
 <head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <title>Login with Google Account using PHP</title>
  <meta content='width=device-width, initial-scale=1, maximum-scale=1' name='viewport'/>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
  <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
  
 </head>
 <body>
  <div class="container">
   <br />
   <h2 align="center">Login with Google Account using PHP</h2>
   <br />
   <div class="panel panel-default">
   <?php
   if($login_button == '')
   {
    echo '<div class="panel-heading">Welcome User</div><div class="panel-body">';
    echo '<img src="'.$_SESSION["user_image"].'" class="img-responsive img-circle img-thumbnail" />';
    echo '<h3><b>Name :</b> '.$_SESSION['user_first_name'].' '.$_SESSION['user_last_name'].'</h3>';
    echo '<h3><b>Email :</b> '.$_SESSION['user_email_address'].'</h3>';
    echo '<h3><a href="logout.php">Logout</h3></div>';
   }
   else
   {
    echo '<div align="center">'.$login_button . '</div>';
   }
   ?>
   </div>
  </div>
 </body>
</html>


logout.php



<?php

//logout.php

include('config.php');

//Reset OAuth access token
$google_client->revokeToken();

//Destroy entire session data.
session_destroy();

//redirect page to index.php
header('location:index.php');

?>


Therefore, this is a complete process of using the Google API client library for PHP login with the Google account.