Implementing Google login system in your website is very easy with OAuth2 support, a simple and standard authorization method. With minimal line of PHP codes, we can acquire required user information from Google, and use the information to register or login users on click of a button. In this article let us learn to easily register/login users using Google PHP API library and MySQL.
This tutorial requires only one PHP page, all task are performed within the page with support of Google APIs Client Library for PHP. These library files are included in downloadable file at the bottom of this page, also look at their sample code, because this tutorial is based on it.
Database Table
Run SQL query below to create a new MySQL table called “google_users” using phpMyAdmin. There are five columns in the database table for the tutorial, and you will find that the length of Google profile IDs are too long (21 characters), it is not possible to accommodate these IDs into INT or BIGINT field, hence I have used DECIMAL(21,0), but you can also store them as string in VARCHAR field and create a separate auto increment primary field.
CREATE TABLE IF NOT EXISTS `google_users` (
`google_id` decimal(21,0) NOT NULL,
`google_name` varchar(60) NOT NULL,
`google_email` varchar(60) NOT NULL,
`google_link` varchar(60) NOT NULL,
`google_picture_link` varchar(60) NOT NULL,
PRIMARY KEY (`google_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
Login and Process Page
All applications that access a Google API must be registered through the APIs Console. The result of this registration process is a set of values that are known to both Google and your application (e.g. client_id, client_secret, JavaScript origins, redirect_uri, etc.). The set of values generated varies based on what type of application you are building.
Replace Google settings with Client keys and Developer key you’ve obtained from Google, and MySql database details of your website.
Problem in getting the Developer Key and Creating Google OAuth API Keys ??
Here you can see the tutorial. Click here
You need to read comment lines in the PHP code to understand how Google login system works. This is the simplest form of Google login system, if you are familiar with Facebook Login System, then it wont be that hard to understand, because it works pretty much the same.
When user clicks login link, user is redirected to Google Authentication page, once user grants the basic permission to access their data, user is again redirected back to website with Authentication code. The code is used to obtain Access Token, using Access Token the application can access current user data from Google, which could be used to register and login the user.
Download the sample code and paste the “src” folder under “lib” directory present on the root of your cakePHP folder.
Now create a file UsersController.php in your controller and write the following code:
<?php
class UsersController extends AppController
{
function login()
{
########## Google Settings.. Client ID, Client Secret #############
$google_client_id = 'xxxxxxxxxx.apps.googleusercontent.com';
$google_client_secret = 'xxxxxxxxxxxxxxxxxxxx';
$google_redirect_url = 'http://localhost/google-login/';
$google_developer_key = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
//include google api files
require_once 'src/Google_Client.php';
require_once 'src/contrib/Google_Oauth2Service.php';
$gClient = new Google_Client();
$gClient->setApplicationName('Login to localhost');
$gClient->setClientId($google_client_id);
$gClient->setClientSecret($google_client_secret);
$gClient->setRedirectUri($google_redirect_url);
$gClient->setDeveloperKey($google_developer_key);
$google_oauthV2 = new Google_Oauth2Service($gClient);
//If user wish to log out, we just unset Session variable
if (isset($_REQUEST['reset']))
{
$this->set('msg', 'Logout');
//unset($_SESSION['token']);
$this->Session->delete('token');
$gClient->revokeToken();
header('Location: ' . filter_var($google_redirect_url, FILTER_SANITIZE_URL));
}
//Redirect user to google authentication page for code, if code is empty.
//Code is required to aquire Access Token from google
//Once we have access token, assign token to session variable
//and we can redirect user back to page and login.
if (isset($_REQUEST['code']))
{
$gClient->authenticate($_REQUEST['code']);
$this->Session->write('token', $gClient->getAccessToken());
$this->redirect(filter_var($google_redirect_url, FILTER_SANITIZE_URL), null, false);
//header('Location: ' . filter_var($google_redirect_url, FILTER_SANITIZE_URL));
return;
}
if ($this->Session->read('token'))
{
$gClient->setAccessToken($this->Session->read('token'));
}
if ($gClient->getAccessToken())
{
//Get user details if user is logged in
$user = $google_oauthV2->userinfo->get();
$user_id = $user['id'];
$user_name = filter_var($user['name'], FILTER_SANITIZE_SPECIAL_CHARS);
$email = filter_var($user['email'], FILTER_SANITIZE_EMAIL);
$profile_url = filter_var($user['link'], FILTER_VALIDATE_URL);
$profile_image_url = filter_var($user['picture'], FILTER_VALIDATE_URL);
$personMarkup = "$email<div><img src='$profile_image_url?sz=50'></div>";
$this->Session->write('token', $gClient->getAccessToken());
}
else
{
//get google login url
$authUrl = $gClient->createAuthUrl();
}
if(isset($authUrl)) //user is not logged in, show login button
{
$this->set('authUrl', $authUrl);
}
else // user logged in
{
$result = $this->User->find('count', array('conditions' => array('google_id' => $user_id)));
if($result > 0)
{
$msg = 'Welcome back '.$user_name.'!<br />';
$msg .= '<br />';
$msg .= '<img src="'.$profile_image_url.'" width="100" align="left" hspace="10" vspace="10" />';
$msg .= '<br />';
$msg .= ' Name: '.$user_name.'<br />';
$msg .= ' Email: '.$email.'<br />';
$msg .= '<br />';
$this->set('msg', $msg);
}
else
{
$msg1 = 'Hi '.$user_name.', Thanks for Registering!';
$msg1 .= '<br />';
$msg1 .= '<img src="'.$profile_image_url.'" width="100" align="left" hspace="10" vspace="10" />';
$msg1 .= '<br />';
$msg1 .= ' Name: '.$user_name.'<br />';
$msg1 .= ' Email: '.$email.'<br />';
$msg1 .= '<br />';
$this->set('msg', $msg1);
$this->User->query("INSERT INTO google_users (google_id, google_name, google_email, google_link, google_picture_link) VALUES ($user_id, '$user_name', '$email', '$profile_url', '$profile_image_url')");
}
}
}
}
Now create a Model User.php
<?php
class User extends AppModel
{
var $name = 'User';
var $useTable = 'google_users';
}
?>
Now for the view create folder Users and in that create login.ctp file
<?php
//HTML page start
echo '<h1>Login with Google</h1>';
if(isset($authUrl)) //user is not logged in, show login button
{
echo '<a class="login" href="'.$authUrl.'"><img src="'.WEB_ROOT.'google-login-button.png" /></a>';
}
else
{
echo $msg;
echo '<p><a class="logout" href="?reset=1">Logout</a></p>';
}
?>
Now go to app/Config/routes.php and add the following code
if (!defined('WEB_ROOT'))
{
define('WEB_ROOT', "http://".$_SERVER['HTTP_HOST']."/yourdomainname/images/");
}
after the line Router::connect(‘/’, array(‘controller’ => ‘pages’, ‘action’ => ‘display’, ‘home’));
Hey Sid! Thanks for the great tutorial. We added in the code as per your instructions and we’ve wound up with this error message: “Parse error: syntax error, unexpected ‘:’ in /home/avalanch/public_html/app/Config/routes.php on line 33”
Any idea what the problem might be?
Thanks,
Andrew
Hey Andrew I just updated the code. Try this code I think the line we have to write on app/Config/routes.php was wrong.
hi
Nice article….
i want how to login with twitter in cakephp…..
Hi , Nice article .I will be trying soon this.
i am having one query as with this authentication can i also access gmail also or not. as i am mostly looking for gmail.
Please let me know as i need it urgently.
This code is for login to your website with your Google account.
Hey Siddharth, great article. Any chance you could update it to include the latest Google APIs client library for PHP and Google+ Sign-In (that Google’s migrating all old methods to)? https://developers.google.com/+/web/signin/server-side-flow
Haven’t tried the new API, will update soon. Thanks for liking the post.
Thanks a lot for this tutorial. I’m now able to run the Login Google when I stumbled on it for 3 hours with the official documentation.