LightOpneID is a php openid class that can be used to login with openid services like Google and Twitter.

In this example, I wanted to show how to use LightOpenID to login to remote sites with Google, and also returning the Google email address associated with the account.

Once LightOpenID is download, take a look at the example-google.php file. If you just run this file along with the openid.php file on your webserver it will work just fine. However, if you want it to return the email address associated with the account you will need to change the code a bit.

Lines 1-12 are what handles the auth redirect and step-up of the authentication with google. Make sure you place your domain where it states localhost. Then after line 9 which states the identity:

$openid->identity = 'https://www.google.com/accounts/o8/id';

Add the line:

$openid->required = array('namePerson/friendly', 'contact/email');

Therefore, the result should look something like this:

<?php
require 'openid.php';
try {
    $openid = new LightOpenID('example.com');
    if(!$openid->mode) {
        if(isset($_GET['login'])) {
            $openid->identity = 'https://www.google.com/accounts/o8/id';
            $openid->required = array('namePerson/friendly', 'contact/email');
            header('Location: ' . $openid->authUrl());
        }
?>

This code tells Google that you want the email address also returned in the authentication process. Now the next step to get to the email address from the class when a valid authentication has occurred.

Therefore, I’m going to change up the return code (aka elseif statement) to get and display the returned email variable. To do this I’m going to change the echo string into an if else statement since I need to add a few lines of code. String to be changed:

echo 'User ' . ($openid->validate() ? $openid->identity . ' has ' : 'has not ') . 'logged in.';

The return variables from google are stored in a associative array, this array can be accessed from calling this function:

$openid->getAttributes();

The index needed to access the variable is called ‘contact/email’ which will allow you to access the email address information.

Therefore, the resulting code looks like this:

if($openid->validate()) {
	$returnVariables = $openid->getAttributes();
	echo 'User ' . $openid->identity . ' has logged in with this email address ' . $returnVariables['contact/email'];
} else {
	echo 'User has not logged in.';
}