Click here to Skip to main content
15,894,017 members
Articles / Programming Languages / PHP
Tip/Trick

Login Google using PHP

Rate me:
Please Sign up or sign in to vote.
4.00/5 (1 vote)
27 Sep 2019CPOL 5.3K   1   1
Introduction Login Google using PHP

Here, I'm going to share a very simple example for Login Google using PHP. First of all, we need set up Google API Console.

https://hoanguyenit.com/public/upload/images/google-console-api-key-01.png

Image 2

After setting up Google API Console, we have Client ID and Client secret. Okay, next step, we need library installing from Google to project.

$ composer require google/apiclient:"^2.0"

or your download: https://github.com/googleapis/google-api-php-client/releases

Ok, we have to project directory create define.php file, you can copy the following code given below, paste to file define.php.

PHP
<?php
    //set define login google
    define('GOOGLE_APP_ID','CLIENG_ID');
    define('GOOGLE_APP_SECRET','CLIENT_SECRET');
    define('GOOGLE_APP_CALLBACK_URL','http://localhost/LoginGoogle/redirect-google.php');
    define('LOCALHOST','localhost');
    define('USERNAME','root');
    define('PASSWORD','');
    define('DATABASE','ABC');
?>

Next step, we need to project directory create redirect-google.php file, you can copy the following below code, pass to it:

PHP
<?php
    require_once('define.php');

    /**
     * SET CONNECT 
     */
    $conn = mysqli_connect(LOCALHOST,USERNAME,PASSWORD,DATABASE);
    if (!$conn) {
        echo "Error: Unable to connect to MySQL." . PHP_EOL;
        echo "Debugging errno: " . mysqli_connect_errno() . PHP_EOL;
        echo "Debugging error: " . mysqli_connect_error() . PHP_EOL;
        exit;
    }
    

    /**
     * CALL GOOGLE API
     */
    require_once 'google-api-php-client-2.4.0/vendor/autoload.php';
    $client = new Google_Client();
    $client->setClientId(GOOGLE_APP_ID);
    $client->setClientSecret(GOOGLE_APP_SECRET);
    $client->setRedirectUri(GOOGLE_APP_CALLBACK_URL);
    $client->addScope("email");
    $client->addScope("profile");
   
    if (isset($_GET['code'])) {
        $token = $client->fetchAccessTokenWithAuthCode($_GET['code']);
       // print_r($token);
        $client->setAccessToken($token['access_token']);

        // get profile info
        $google_oauth = new Google_Service_Oauth2($client);
        $google_account_info = $google_oauth->userinfo->get();
        $email =  $google_account_info->email;
        $name =  $google_account_info->name;
       // print_r($google_account_info);
       /**
        * CHECK EMAIL AND NAME IN DATABASE
        */
        $check = "SELECT * FROM `users` WHERE `email`='".$email."' and `name`='".$name."'";
        $result = mysqli_query($conn,$sql);
        $rowcount=mysqli_num_rows($result);
        if($rowcount>0){
            /**
             * USER EXITS
             */
            header('location:home');
        }
        else{
            /**
             * INSERT USER TO DATABASE
             * AFTER INSERT, YOU CAN HEADER TO HOME
             */
        }
       
    } else {
        /**
         * IF YOU DON'T LOGIN GOOGLE
         * YOU CAN SEEN AGAIN GOOGLE_APP_ID, GOOGLE_APP_SECRET, GOOGLE_APP_CALLBACK_URL
         */
        echo "<a href='".$client->createAuthUrl()."'>Google Login</a>";
    }

Okay, we have configution success, you can run test: http://localhost/LoginGoogle/redirect-google.php. you will see it.

Image 3

Success!

History

  • 27th September, 2019: Initial version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Web Developer Sinbadgroup
Vietnam Vietnam
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionCode not working when returning back to site Pin
Member 146407201-Nov-19 0:33
Member 146407201-Nov-19 0:33 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.