If you are looking for tutorial on How to Create Login by using Google Account with Codeigniter framework, then you land on right page, because in this post we have describe step by step process for integrate Google Account login in Codeigniter framework.
Currently, most of the website has provide feature like Login into their website by using Google Account. By using Google Login account user can directly login into website without register into that website, and user can directly enter website without registration.
Now in your mind one question will aris, how can we use Google Account for login into website. So for this Google has provide api for use Google account for login into website. Google has provide OAuth 2.0 API, which is open authentication api and it is very powerful for authenticate user login. By using this API, we can access user data from server and acter authenticate user data via Google account, user can get access into website.
So, In this tutorial, we will learn How can we integrate Google Open authentication login into Codeigniter website. Below you can find step by step process for integration of Login using Google Account in Codeigniter Framework.
- Create Google API Credential
- Download Google API php client library
- Define Autoload library
- Define Base Url of Codeigniter Application
- Make Database connection
- Create Controller
- Create Model
- Create View file
Create Google API Credential
For get Google API Credential, we need Google Account, if you have Google Account then you to first login into you account.
1 - If you are login into Google account, then you have to https://console.developers.google.com/ url.
2 - Once you have open above link, then first you have to create new project by click on create project link.
3 - After click on project link then new page will open, and here we have enter project name and click on create button.
4 - Next you can see newly created project on web page. And after this we have to click on OAuth consent screen link.
5 - After click on OAuth consent screen, then after new page has been load in browser, and here we can see two User Type option, and from that option we have to select External and click on Create button.
6 - Once we have click on Create button, then web page has redirect to new page, and on this page, we have to define Application Name and after this click on Save button.
7 - When we have click on Save button, then web page has redirect to this page. Here we can see our application details. Next we have to click on Credentials link at the left side menu.
8 - After click on Credentials link, then Credentials web page has been load in browser. And here we have to click on CREATE CREDENTIALS button.
9 - Once we have click on CREATE CREDENTIALS button, then one dropdown has been appear on web page with four option. And from that option, we have to select OAuth client ID link.
10 - When we have click on OAuth client ID option, then one new page has been load in browser and here we have to define Application Type from different option. So, from that option, we have to select Web Application.
11 - Once we have select Web Application, then below that field new field has been appear and in that field, we have to enter Name field details and define Authorized redirect Uris. This is for use with request from server, and lastly we have to click on Create button.
12 - Once we have click on Create button, then our Application has been register, and then after new page has been load with our application Client ID and Client secret key will appear on web page. We have to use both key in Codeigniter framework for make Login using Google Account.
2 - Download Google API php client library
Once we have get Google Client ID and Client Secret key, so next we have to download Google API Client Library for PHP script. So for this, first we have go to command prompt in which we have already install Composer command, and after this we have go to library folder of codeigniter framework in which we have to download library and run following command.
composer require google/apiclient:"^2.0"
This command will download Google API Client Library for PHP language in your define directory. Next we have proceed for write code in Codeigniter framework.
3 - Define Autoload library
In Codeigniter framework, we have to first define autoload library like database and session, so once we have define library, then we have do not want to again and again load in every method. For this we have to open application/config/autoload.php file.
$autoload['libraries'] = array('database','session');
4 - Define Base Url of Codeigniter Application
In Next step we have to define base url of your Codeigniter application. This is root url of you codeigniter application. For define Base url, we have to open application/config/config.php and write base url of your application.
$config['base_url'] = 'http://localhost/tutorial/codeigniter/';
5 - Make Database connection
Once we have define base url, next we want to make Msyql database connection. For this we have to open application/config/database.php and in that file we have to define database configuration.
$db['default'] = array(
'dsn' => '',
'hostname' => 'localhost',
'username' => 'root',
'password' => '',
'database' => 'codeigniter_chat',
'dbdriver' => 'mysqli',
'dbprefix' => '',
'pconnect' => FALSE,
'db_debug' => (ENVIRONMENT !== 'production'),
'cache_on' => FALSE,
'cachedir' => '',
'char_set' => 'utf8',
'dbcollat' => 'utf8_general_ci',
'swap_pre' => '',
'encrypt' => FALSE,
'compress' => FALSE,
'stricton' => FALSE,
'failover' => array(),
'save_queries' => TRUE
);
6 - Create Controller
In Codeigniter framework, controller is used for handle http request. In Codeigniter framework controller class file has been store under application/controllers folder Here we have create controller with Google_login.php file name. In this controller here we have make following method.
__construct() - This is magic function code will be executed every time, when object of this class has been created.
login() - This method will communicate with Google Login Api by using Google API client library for PHP script. In this method we to set ClientID, ClientSecret key and Redirect Uri which we have to define at the time creating credential process. Once this all has been set then we can send login request to Google server, then from server this method will received access token and based on that token user can login into website and get user data. If user data already store in our database, then this function will update data, otherwise it will insert user data in our database.
logout() - This method will received request from user to get permission for logout from system. In this method it has simply delete data from session variable and it will redirect page to login.
application/controllers/Google_login.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Google_login extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->model('google_login_model');
}
function login()
{
include_once APPPATH . "libraries/vendor/autoload.php";
$google_client = new Google_Client();
$google_client->setClientId(''); //Define your ClientID
$google_client->setClientSecret(''); //Define your Client Secret Key
$google_client->setRedirectUri(''); //Define your Redirect Uri
$google_client->addScope('email');
$google_client->addScope('profile');
if(isset($_GET["code"]))
{
$token = $google_client->fetchAccessTokenWithAuthCode($_GET["code"]);
if(!isset($token["error"]))
{
$google_client->setAccessToken($token['access_token']);
$this->session->set_userdata('access_token', $token['access_token']);
$google_service = new Google_Service_Oauth2($google_client);
$data = $google_service->userinfo->get();
$current_datetime = date('Y-m-d H:i:s');
if($this->google_login_model->Is_already_register($data['id']))
{
//update data
$user_data = array(
'first_name' => $data['given_name'],
'last_name' => $data['family_name'],
'email_address' => $data['email'],
'profile_picture'=> $data['picture'],
'updated_at' => $current_datetime
);
$this->google_login_model->Update_user_data($user_data, $data['id']);
}
else
{
//insert data
$user_data = array(
'login_oauth_uid' => $data['id'],
'first_name' => $data['given_name'],
'last_name' => $data['family_name'],
'email_address' => $data['email'],
'profile_picture' => $data['picture'],
'created_at' => $current_datetime
);
$this->google_login_model->Insert_user_data($user_data);
}
$this->session->set_userdata('user_data', $user_data);
}
}
$login_button = '';
if(!$this->session->userdata('access_token'))
{
$login_button = '<a href="'.$google_client->createAuthUrl().'"><img src="'.base_url().'asset/sign-in-with-google.png" /></a>';
$data['login_button'] = $login_button;
$this->load->view('google_login', $data);
}
else
{
$this->load->view('google_login', $data);
}
}
function logout()
{
$this->session->unset_userdata('access_token');
$this->session->unset_userdata('user_data');
redirect('google_login/login');
}
}
?>
7 - Create Model
Model class generally used for database related operation. In codeigniter framework, Model class has been store under application/models folder. Here we have create Models class with Google_login_model.php file. In this class we have make following method.
Is_already_register($id) - This method has been check user with $id variable value is already store in chat_user table or not. If user data is available then it will return true, otherwise it will return false.
Update_user_data($data, $id) - This method will update chat_user table data based on value of $id variable value.
Insert_user_data($data) - This method will insert data into chat_user table.
application/models/Google_login_model.php
<?php
class Google_login_model extends CI_Model
{
function Is_already_register($id)
{
$this->db->where('login_oauth_uid', $id);
$query = $this->db->get('chat_user');
if($query->num_rows() > 0)
{
return true;
}
else
{
return false;
}
}
function Update_user_data($data, $id)
{
$this->db->where('login_oauth_uid', $id);
$this->db->update('chat_user', $data);
}
function Insert_user_data($data)
{
$this->db->insert('chat_user', $data);
}
}
?>
8 - Create View file
This file is used for display html output in browser. In Codeigniter framework view file has been store in application/views folder. Here we have create views file with google_login.php name.
application/views/google_login.php
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Login with Google in Codeigniter</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 using Google Account with Codeigniter</h2>
<br />
<div class="panel panel-default">
<?php
if(!isset($login_button))
{
$user_data = $this->session->userdata('user_data');
echo '<div class="panel-heading">Welcome User</div><div class="panel-body">';
echo '<img src="'.$user_data['profile_picture'].'" class="img-responsive img-circle img-thumbnail" />';
echo '<h3><b>Name : </b>'.$user_data["first_name"].' '.$user_data['last_name']. '</h3>';
echo '<h3><b>Email :</b> '.$user_data['email_address'].'</h3>';
echo '<h3><a href="'.base_url().'google_login/logout">Logout</h3></div>';
}
else
{
echo '<div align="center">'.$login_button . '</div>';
}
?>
</div>
</div>
</body>
</html>
So, this is complete step by step process for How to implement Codeigniter Login application by using Google Account. If you have still not understand code, then you can also view video tutorial of this post also which you can find at the top of this post.
hello "webslesson", its not working on localhost !
ReplyDelete['error' => "
Type: GuzzleHttp\Exception\RequestException
Message: cURL error 60: SSL certificate problem: unable to get local issuer certificate (see https://curl.haxx.se/libcurl/c/libcurl-errors.html)
Filename: C:\xampp\htdocs\ci_insert\application\libraries\google_api\vendor\guzzlehttp\guzzle\src\Handler\CurlFactory.php
Line Number: 201
" ];
i think it's a ssl issue ? how can resolve it ?
if you use PHP version 7.2,upgrade to php 7.4 and that work for me
Deletewhen i refresh page it create error
ReplyDeleteType: Error
ReplyDeleteMessage: Class 'Google_Client' not found
have you found a solution?
DeleteA PHP Error was encountered
ReplyDeleteSeverity: Warning
Message: count(): Parameter must be an array or an object that implements Countable
Filename: Handler/CurlFactory.php
Line Number: 67
Error this code not working
ReplyDeleteI'm not found google api client for windows 10
where is de database?
ReplyDeleteIts not working. It would be helpful if you could help it out.
ReplyDeleteA PHP Error was encountered
Severity: Warning
Message: count(): Parameter must be an array or an object that implements Countable
Filename: Handler/CurlFactory.php
Line Number: 67
In the libraries folder, no vendor folder has come after running composer require google/apiclient:"^2.0" command. please, suggest to me what happened there.
ReplyDeletein the root directory
DeleteIts work great sir thanks for all
ReplyDeletehow to get $_GET["code"] variable
ReplyDeletecan not download "Google API Client Library for PHP script." by composer. Error shows:: [RuntimeException]
ReplyDeleterequire-dev.mikey179/vfsStream is invalid, it should not contain uppercase characters. Please use mikey179/vfsstrea
m instead.
Please help......
change the path to downoad composer and google client api .. it will work
Deletego to composer.json change mikey179/vfsStream to mikey179/vfsstream
Deletereturning
ReplyDeleteArray ( [error] => invalid_client [error_description] => Unauthorized )
Please help
Message: include_once(mydrive:\xampp\htdocs\myprojectDirectory\application\libraries/vendor/autoload.php): failed to open stream: No such file or directory
ReplyDeleteHow to resolve below error?
ReplyDeleteSeverity: Warning
Message: count(): Parameter must be an array or an object that implements Countable
Filename: Handler/CurlFactory.php
Line Number: 67
A PHP Error was encountered
ReplyDeleteSeverity: Warning
Message: Trying to access array offset on value of type null
Filename: views/google_login.php
Line Number: 23
Backtrace:
File: C:\xampp\htdocs\tutorial\codeigniter\application\views\google_login.php
Line: 23
Function: _error_handler
File: C:\xampp\htdocs\tutorial\codeigniter\application\controllers\Welcome.php
Line: 23
Function: view
File: C:\xampp\htdocs\tutorial\codeigniter\index.php
Line: 315
Function: require_once
what is solution?
Type: Google_Auth_Exception
ReplyDeleteMessage: Error fetching OAuth2 access token, message: 'invalid_grant: Bad Request'
Filename: /opt/lampp/htdocs/login_google_ci/application/third_party/Google/Auth/OAuth2.php
Line Number: 126
Backtrace:
File: /opt/lampp/htdocs/login_google_ci/application/third_party/Google/Client.php
Line: 128
Function: authenticate
File: /opt/lampp/htdocs/login_google_ci/application/controllers/Wellcome.php
Line: 27
Function: authenticate
File: /opt/lampp/htdocs/login_google_ci/index.php
Line: 315
Function: require_once
how can I resolve this problem?
A PHP Error was encountered
ReplyDeleteSeverity: Warning
Message: Trying to access array offset on value of type null
Filename: views/google_login.php
Line Number: 23
Backtrace:
File: D:\xampp\htdocs\ci_googlelogin\application\views\google_login.php
Line: 23
Function: _error_handler
File: D:\xampp\htdocs\ci_googlelogin\application\controllers\Google_login.php
Line: 13
Function: view
File: D:\xampp\htdocs\ci_googlelogin\index.php
Line: 315
Function: require_once
A PHP Error was encountered
Severity: Warning
Forbidden
ReplyDeleteYou don't have permission to access this resource.
Additionally, a 403 Forbidden error was encountered while trying to use an ErrorDocument to handle the request.
Showing this error.
It will be really helpful if you have a solution.