Login System with Github using OAuth php and mysql

by  
Share:
Login System with Github using OAuth php and mysql

Github is a web-based hosting service for software development projects that use the Git revision control system. It lets you share your projects with the world, get feedback, and contribute to millions of repositories hosted on GitHub. So continuing my “login system with social sites” series with Github now. By far this was the easiest of all I have integrated. Check out how to create a Login System with Github using OAuth php and mysql

View Demo

How login with Github works?

Check out my last posts on Login System with LinkedIn using OAuth php and mysql, Login System with Facebook with php and mysql, Login System with Google using OAuth php and mysql. The working is very similar to that.

  • You will have to create an application with Github to get CLIENT ID and SECRET KEY.
  • After you are done with Step 1 , you will go to the website say “http://demos.aarafacademy.com/login-system-with-github/index.php” where you will click on login with github button.
  • It will redirect you to github_login.php which will redirect to Github Site, where you will have to login with your Github Credentials and then allow the permission to the application. It will redirect you back to your github_login.php
  • If there is any error, it will send you back to index.php, or if everything is perfect it will check the database for existing email ID. If email ID does not exist it will save it with your name and email ID. and redirect to home.php. If email ID is already present in the database it will just redirect to home.php with welcome message.

Workflow of Login System with Github using OAuth php and mysql

 

How to create a Github Application

Create an aplication on Github to get CLIENT ID and SECRET KEY. Given below is the powerpoint presentation which will guide you through the process of making the a Github Application.

 

Integration of Github with OAuth PHP and MySQL

First of all create a database “login_system” and create a table “users.

CREATE DATABASE IF NOT EXISTS login_system;
USE login_system;
CREATE TABLE IF NOT EXISTS `users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) NOT NULL,
  `email` varchar(255) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;

Set all your credentials in config.php
// database related
define('DB_DRIVER', 'mysql');
define('DB_SERVER', 'localhost');
define('DB_SERVER_USERNAME', 'root');
define('DB_SERVER_PASSWORD', '');
define('DB_DATABASE', 'login_system');

// try connecting with database
try {
  $DB = new PDO(DB_DRIVER . ':host=' . DB_SERVER . ';dbname=' . DB_DATABASE, DB_SERVER_USERNAME, DB_SERVER_PASSWORD, $dboptions);
} catch (Exception $ex) {
  echo $ex->getMessage();
  die;
}

// Github and your website related credentials
define("CLIENT_ID", "your api key");
define("SECRET_KEY", "your api secret");
// change with your site URL
define("SITE_URL", "http://demos.aarafacademy.com/login-system-with-github/");
define("REDIRECT_URL", SITE_URL."github_login.php");
// Set the scope 
define("SCOPE", 'user' );
define("LOGOUT_URL", SITE_URL."logout.php");

Set your login and logout URL in index.php and home.php
<a href="github_login.php">
  Login with LinkedIn
</a>

<a href="<?php echo LOGOUT_URL; ?>">
  Logout
</a>

Now the main part github_login.php. Create an oauth object and try to connect with linkedin and get a response.
require('http.php');
require('oauth_client.php');
require('config.php');

$client = new oauth_client_class;
$client->debug = false;
$client->debug_http = true;
$client->redirect_uri = REDIRECT_URL;

$client->client_id = CLIENT_ID;
$application_line = __LINE__;
$client->client_secret = SECRET_KEY;

if (strlen($client->client_id) == 0 || strlen($client->client_secret) == 0)
  die('Please go to Github Apps page');

$client->scope = SCOPE;
if (($success = $client->Initialize())) {
  if (($success = $client->Process())) {
    if (strlen($client->authorization_error)) {
      $client->error = $client->authorization_error;
      $success = false;
    } elseif (strlen($client->access_token)) {
      $success = $client->CallAPI(
              'https://api.github.com/user', 'GET', array(), array('FailOnAccessError' => true), $user);
    }
  }
  $success = $client->Finalize($success);
}
if ($client->exit) exit;

You will get user data on successfull sign in. Save the email id and name if they dont exist in database. There are cases where your dont provide their name and email so in that case throw an error message to them.
if ($success) {
  // Now check if user exist with same email ID
  $sql = "SELECT COUNT(*) AS count from users where email = :email_id";
  try {
    $stmt = $DB->prepare($sql);
    $stmt->bindValue(":email_id", $user->emailAddress);
    $stmt->execute();
    $result = $stmt->fetchAll();

    if ($result[0]["count"] > 0) {
      // User Exist 

      $_SESSION["name"] = $user->name;
      $_SESSION["email"] = $user->email;
      $_SESSION["new_user"] = "no";
    } else {
      // New user, Insert in database
      $sql = "INSERT INTO `users` (`name`, `email`) VALUES " . "( :name, :email)";
      $stmt = $DB->prepare($sql);
      $stmt->bindValue(":name", $user->name);
      $stmt->bindValue(":email", $user->email);
      $stmt->execute();
      $result = $stmt->rowCount();
      if ($result > 0) {
        $_SESSION["name"] = $user->name;
        $_SESSION["email"] = $user->email;
        $_SESSION["new_user"] = "yes";
        $_SESSION["e_msg"] = "";
      }
    }
  } catch (Exception $ex) {
    $_SESSION["e_msg"] = $ex->getMessage();
&nbsp;&nbsp; &nbsp;$_SESSION["e_msg"] .= "<br>Please set your github profile name/email.";
  }

  $_SESSION["user_id"] = $user->id;
} else {
  $_SESSION["e_msg"] = $client->error;
}

The final part is to display the results on the user screen i.e. on home.php
<?php if ($_SESSION["new_user"] == "yes") { ?>
<h2>Thank you <?php echo $_SESSION["name"] ?>, for registering with us!!!</h2>
<?php } else { ?>
<h2>Welcome back <?php echo $_SESSION["name"] ?>!!!</h2>
  <?php } ?>
<h5>Your email id is: <span style="text-decoration:underline;"><?php echo $_SESSION["email"]; ?></span></h5>

View Demo
Share to download the Source Codes for FREE!
We're glad to give free downloads, but we need your love to carry on making that.
Please support us by sharing the page.

Get the latest updates directly in your inbox for FREE: Subscribe here

Share your feedback / let me know your doubts regarding this tutorial in the comment box given below.

Share:
Hasan

Shahrukh Khan (Hasan)

A software engineer who's a die-hard coder, blogger, dreamer and mentor with years of expertise in web development. Know more...

Related Posts

Narendra on

I am not getting user data null value is storing in both $user -> name and $user -> email
could you please help me to overcome this issue

Reply

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.