Note: This example is provided for illustrative purposes only! This tutorial shows how to integrate HybridAuth into an existing login page. The code however, is incomplete, insecure, relatively untested and not to be used in production AS-IS.



Download this example source code


Let say we have an existen login system on a website on which we want to let users to authenticate using Facebook, Twitter and LinkedIn.

Lets also assume our databse.users table look like this:

CREATE TABLE IF NOT EXISTS `users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `email` varchar(200) NOT NULL,
  `password` varchar(200) NOT NULL,
  `first_name` varchar(200) NOT NULL,
  `last_name` varchar(200) NOT NULL,
  `created_at` datetime NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `email` (`email`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 ;

and login.php form is something like this:

<form>
	<fieldset>
		<legend>Sign-in form</legend>
		email   : <input type="text" name="email" /><br />
		password: <input type="password" name="password" /><br />

		<input type="submit" value="Sign-in" />
	</fieldset>
</form>

1. First we need some awesome Social sign in buttons to add to our forms, and we are going to use those created by komodomedia.com (you may also like these CSS social sign-in buttons made by samcollins).

2. Then we add three buttons for these social networks to our login form, and each one of them will link to login.php providing the selected provider name as parameter: login.php?provider={provider_name}

<fieldset>
    <legend>Or use another service</legend>

    <a href="login.php?provider=facebook"><img src="images/buttons/facebook.gif" /></a><br />
    <a href="login.php?provider=twitter" ><img src="images/buttons/twitter.gif"  /></a><br />
    <a href="login.php?provider=linkedin"><img src="images/buttons/linkedin.gif" /></a>
</fieldset>

3.. Add 2 fields ( Provider name, Provider user ID) to databse.users. Then create the couple (provider_name, provider_uid) to be able to identify the connected user:

ALTER TABLE `users` ADD `hybridauth_provider_name` VARCHAR(255) NOT NULL COMMENT 'Provider name';
ALTER TABLE `users` ADD `hybridauth_provider_uid` VARCHAR(255) NOT NULL COMMENT 'Provider user ID';

CREATE UNIQUE INDEX hybridauth_idx ON users (hybridauth_provider_name, hybridauth_provider_uid);

-- `hybridauth_provider_name` is the provider name if the user is signed up with hybridauth
-- `hybridauth_provider_uid`  is the Unique user ID on the used provider.

4. Next, we need to alter login.php flow by handling requested provider parameter:

<?php
// if page requested by submitting login form
if( isset( $_REQUEST["email"] ) && isset( $_REQUEST["password"] ) )
{
	$user_exist = get_user_by_email_and_password( $_REQUEST["email"], $_REQUEST["password"] );

	// user exist?
	if( $user_exist )
	{
		// set the user as connected and redirect him to a home page or something
		$_SESSION["user_connected"] = true;

		header("Location: http://www.example.com/user/home.php");
	}

	// wrong email or password?
	else
	{
		// redirect him to an error page
		header("Location: http://www.example.com/login-error.php");
	}
}

// else, if login page request by clicking a provider button
elseif( isset( $_REQUEST["provider"] ) )
{
	// the selected provider
	$provider_name = $_REQUEST["provider"];

	try
	{
		// inlcude HybridAuth library
		// change the following paths if necessary
		$config   = dirname(__FILE__) . '/library/config.php';
		require_once( "library/Hybrid/Auth.php" );

		// initialize Hybrid_Auth class with the config file
		$hybridauth = new Hybrid_Auth( $config );

		// try to authenticate with the selected provider
		$adapter = $hybridauth->authenticate( $provider_name );

		// then grab the user profile
		$user_profile = $adapter->getUserProfile();
	}

	// something went wrong?
	catch( Exception $e )
	{
		header("Location: http://www.example.com/login-error.php");
	}

	// check if the current user already have authenticated using this provider before
	$user_exist = get_user_by_provider_and_id( $provider_name, $user_profile->identifier );

	// if the used didn't authenticate using the selected provider before
	// we create a new entry on database.users for him
	if( ! $user_exist )
	{
		create_new_hybridauth_user(
			$user_profile->email,
			$user_profile->firstName,
			$user_profile->lastName,
			$provider_name,
			$user_profile->identifier
		);
	}

	// set the user as connected and redirect him
	$_SESSION["user_connected"] = true;

	header("Location: http://www.example.com/user/home.php");
}

5. Finally we need define and implement get_user_by_provider_and_id() and create_new_hybridauth_user() to respectively find a user by a given unique index (provider_name, provider_uid) on databse.users, and to register new users connected via Hybridauth library.

On the snippets below, we provide some of the functions used on (4.):

<?php
// You know how it works...
$link = mysqli_connect( "localhost", "my_user", "my_password", "database" );

/*
* We need this function cause I'm lazy
**/
function mysqli_query_excute( $sql )
{
	global $link;

	$result = mysqli_query( $link, $sql );

	if(  ! $result )
	{
		die( printf( "Error: %s\n", mysqli_error( $link ) ) );
	}

	return $result->fetch_object();
}

/*
* get the user data from database by email and password
**/
function get_user_by_email_and_password( $email, $password )
{
	return mysqli_query_excute( "SELECT * FROM users WHERE email = '$email' AND password = '$password'" );
}

/*
* get the user data from database by provider name and provider user id
**/
function get_user_by_provider_and_id( $provider_name, $provider_user_id )
{
	return mysqli_query_excute( "SELECT * FROM users WHERE hybridauth_provider_name = '$provider_name' AND hybridauth_provider_uid = '$provider_user_id'" );
}

/*
* get the user data from database by provider name and provider user id
**/
function create_new_hybridauth_user( $email, $first_name, $last_name, $provider_name, $provider_user_id )
{
	// let generate a random password for the user
	$password = md5( str_shuffle( "0123456789abcdefghijklmnoABCDEFGHIJ" ) );

	mysqli_query_excute(
		"INSERT INTO users
		(
			email,
			password,
			first_name,
			last_name,
			hybridauth_provider_name,
			hybridauth_provider_uid,
			created_at
		)
		VALUES
		(
			'$email',
			'$password',
			'$first_name',
			'$last_name',
			$provider_name,
			$provider_user_id,
			NOW()
		)"
	);
}