Saturday, October 13, 2012

How to make user login with Google Account in your site

In many sites you might have noticed that, there are many options for login. Means to login into that site you can use Google, Yahoo, AOL etc. accounts.

You can integrate Google account for your site very easily. To make this we'll use OpenID.  OpenID provides a safe, elegant and easy way for people to login into your website without having to fill in a registration form. They just have to have an account to one OpenID provider, a Google account for instance, and they will login into your site with this account.



dI'll show you how to implement it with Google Account.

1.) We'll be using a one-file PHP OpenID library that you can download from here. LightOpenID. Just put this file in your project folder.

2.) Now, Here is login.php


< ?php
require_once 'openid.php';
$openid = new LightOpenID("my-domain.com");
 
if ($openid->mode) {
    if ($openid->mode == 'cancel') {
        echo "User has canceled authentication !";
    } elseif($openid->validate()) {
        $data = $openid->getAttributes();
        $email = $data['contact/email'];
        $first = $data['namePerson/first'];
        echo "Identity : $openid->identity ";
        echo "Email : $email";
        echo "First name : $first";
    } else {
        echo "The user has not logged in";
    }
} else {
    echo "Go to index page to log in.";
}
?>

    Note : Replace "myp-domain.com" with your site url.


3.) Now, final step to render the button, let's say on the home page. "index.php"

< ?php
require_once 'openid.php';
$openid = new LightOpenID("my-domain.com");
 
$openid->identity = 'https://www.google.com/accounts/o8/id';
$openid->required = array(
  'namePerson/first',
  'namePerson/last',
  'contact/email',
);
$openid->returnUrl = 'http://my-domain.com/login.php'
?>
 
<a href="< ?php echo $openid->authUrl() ?>">Login with Google





4.) To logout a user,  just destroy  the session.

session_destroy();



Other OpenID providers:

  • Google : https://www.google.com/accounts/o8/id
  • Yahoo  : https://me.yahoo.com
  • AOL    : https://www.aol.com


You can download full demo project from here.

Analysis :