How to Login with Google Account in CodeIgniter

Google OAuth API is the easiest option to integrate login system in the website. Google OAuth login system helps the user to login to the web application using their Google plus account. The main advantages of Google login are the user can login to the web application with their existing Google account without register on the website.

Before you begin to integrate Login with Google in CodeIgniter, check below steps

Step 1: Config (application/config/autoload.php)

$autoload['libraries'] = array('database','email','session');
$autoload['helper'] = array('url', 'file');

Step 2: Google API PHP Client Library (application/third_party/)

public function __construct()
{
	parent::__construct();
	require_once APPPATH.'third_party/src/Google_Client.php';
	require_once APPPATH.'third_party/src/contrib/Google_Oauth2Service.php';
}

Step 3: Google Account button on click and redirect controller function like (google_login())

public function google_login()
{
	$clientId = ''; //Google client ID
	$clientSecret = ''; //Google client secret
	$redirectURL = base_url() . 'Login/google_login/';

	//Call Google API
	$gClient = new Google_Client();
	$gClient->setApplicationName('Login');
	$gClient->setClientId($clientId);
	$gClient->setClientSecret($clientSecret);
	$gClient->setRedirectUri($redirectURL);
	$google_oauthV2 = new Google_Oauth2Service($gClient);

	if(isset($_GET['code']))
	{
		$gClient->authenticate($_GET['code']);
		$_SESSION['token'] = $gClient->getAccessToken();
		header('Location: ' . filter_var($redirectURL, FILTER_SANITIZE_URL));
	}

	if (isset($_SESSION['token'])) 
	{
		$gClient->setAccessToken($_SESSION['token']);
	}

	if ($gClient->getAccessToken()) {
		$userProfile = $google_oauthV2->userinfo->get();
		echo "<pre>";
		print_r($userProfile);
		die;
	} 
	else 
	{
		$url = $gClient->createAuthUrl();
		header("Location: $url");
		exit;
	}
}	

Step 4: Goolge Account Response Output

Array
(
    [id] => 10739576423966946874545
    [email] => example@gmail.com
    [verified_email] => 1
    [name] => Name
    [given_name] => Lastname
    [family_name] => Full name
    [link] => https://plus.google.com/12312456789
    [picture] => https://lh3.googleusercontent.com/-456578312/photo.jpg
    [gender] => male
    [locale] => en
)

PHPCopy

In above finally complete all step and retrieve all data in google account.

Leave a Reply

Your email address will not be published. Required fields are marked *