Archive

October 2015

Browsing

Login System with Google using Php and OAuth Api

Nowadays all are feel irritated to fill the long text box of registration form. So they feel simply registered with Google integration. For website  its also Safe to avoid spam and irrelevant data while login using google.  Most of the website demanded this option. social login has become a most integrated one in all login forms. In this tutorial We will learn how to make a Login System with Google using Php and OAuth Api. User will login with their Google account, give permission to access basic profile, and their name with email will be stored in database.

Demo

What is OAuth (Authorization)

Google APIs use the OAuth 2.0 protocol for authentication and authorization. Google supports common OAuth 2.0 scenarios such as those for web server, installed, and client-side applications.

To begin, obtain OAuth 2.0 client credentials from the Google Developers Console. Then your client application requests an access token from the Google Authorization Server, extracts a token from the response, and sends the token to the Google API that you want to access. For an interactive demonstration of using OAuth 2.0 with Google (including the option to use your own client credentials), experiment with the OAuth 2.0 Playground.

Refer – https://developers.google.com/identity/protocols/OAuth2

Simply- your are the owner of your website and you have all admin privileges, ‘Guest’ want to access your page and surf some stuff unless admin grants him with some additional permissions . you can give some permission relevant to ‘Guest’ Role  without sharing your identity and full privileges. This is exactly done by google  OAuth, allow users to Authorize our page with some privileges.

Let start Coding part for Login System with Google using Php and OAuth Api, before that we need to Register our domain with goolge

Get  CLIENT ID and SECRET KEY

Before Coding We need to get CLIENT ID and SECRET KEY for the google, because before the function we need register our website and get CLIENT ID and SECRET KEY for authentication and authorization to our website

Steps for Getting CLIENT ID and SECRET KEY

Step 1 – Go to the Url code.google.com/apis/console
It will redirect to gmail login page after you login with your goole account. It redirect to Google Developer console.

Note – This developer console is everyhting for create Apis Related to the Google

Login System with Google using Php and OAuth Api

Step 2 – Create a New project with your project nameLogin System with Google using Php and OAuth Api

Step 3 – Click APIs & auth link and click credentials and  Oauth 2.0 client Id

credentials

Login System with Google using Php and OAuth Api

Login System with Google using Php and OAuth Api

Step 4 – Before that create Contest screen for product and email verification Login System with Google using Php and OAuth Api

Login System with Google using Php and OAuth Api

Step 5 – Select web Application and Enter you domain and redirect URL details and then get you credentials

Login System with Google using Php and OAuth Api

Finally you get your CLIENT ID and SECRET KEY.

got client id

Coding Step

Create database and table

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

Create config.php file for configuration with database.. enter Your CLIENT ID and SECRET KEY here and also domain redirect your.

<?php

error_reporting(E_ALL & ~E_DEPRECATED & ~E_NOTICE);
ob_start();
session_start();

define('PROJECT_NAME', 'Login System with Google using Php and OAuth Api - www.Developerdesks.com');

define('DB_DRIVER', 'mysql');
define('DB_SERVER', 'localhost');
define('DB_SERVER_USERNAME', 'root');
define('DB_SERVER_PASSWORD', '');
define('DB_DATABASE', 'google_login');

$dboptions = array(
    PDO::ATTR_PERSISTENT => FALSE,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
    PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8',
);
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;
}

/* make sure the url end with a trailing slash */
define("SITE_URL", "http://demos.developerdesks.com/login-with-google/");
/* the page where you will be redirected for authorzation */
define("REDIRECT_URL", SITE_URL."google_login.php");

/* * ***** Google related activities start ** */
define("CLIENT_ID", "your client ID");  /* Place you Clinet ID here */
define("CLIENT_SECRET", "your client secret");   /* Place you Clinet Secret code here */

/* permission */
define("SCOPE", 'https://www.googleapis.com/auth/userinfo.email '.
		'https://www.googleapis.com/auth/userinfo.profile' );


/* logout both from google and your site **/
define("LOGOUT_URL", "https://www.google.com/accounts/Logout?continue=https://appengine.google.com/_ah/logout?continue=". urlencode(SITE_URL."logout.php"));
/* * ***** Google related activities end ** */
?>

Create redirect URL function google_login.php  and this code for authentication the user with google whether he gave correct credentials or not. if give correct credentials check it ans success page redirect to specified page and insert user data into database.  If it returns error redirect back to index.php. If api returns user details check with database if user email exist and do the necessary accordingly and redirect back to home.php

<?php
require('http.php');  // require for HTTp verification 
require('oauth_client.php');  // function for google Oauth integration
require('config.php');  // require for domain and Client id and secret id verification


$client = new oauth_client_class;

// set the offline access only if you need to call an API
// when the user is not present and the token may expire
$client->offline = FALSE;

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

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

if (strlen($client->client_id) == 0 || strlen($client->client_secret) == 0)
  die('Please go to Google APIs console page ' .
          'http://code.google.com/apis/console in the API access tab, ' .
          'create a new client ID, and in the line ' . $application_line .
          ' set the client_id to Client ID and client_secret with Client Secret. ' .
          'The callback URL must be ' . $client->redirect_uri . ' but make sure ' .
          'the domain is valid and can be resolved by a public DNS.');

/* API permissions
 */
$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://www.googleapis.com/oauth2/v1/userinfo', 'GET', array(), array('FailOnAccessError' => true), $user);
    }
  }
  $success = $client->Finalize($success);
}
if ($client->exit)
  exit;
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->email);
    $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)";    /* Insert user data into database */
      $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();
  }

  $_SESSION["user_id"] = $user->id;
} else {
  $_SESSION["e_msg"] = $client->error;
}
header("location:home.php");
exit;
?>

finally create link for login in index.php

<div>
    <a href="google_login.php">Login with Google
          </a>
  </div>

Create welcome page with logout button in home.php

<div>
   <?php if ($_SESSION["e_msg"] <> "") { ?>
    
      <p><?php echo $_SESSION["e_msg"]; ?></p>
    </div>
  <?php } ?>
 
  <?php if ($_SESSION["new_user"] == "yes") { ?>
    <h2>Thank you <?php echo $_SESSION["name"] ?>, for registering with us!!!</h2>
	<h5>Your email id is: <span style="text-decoration:underline;"><?php echo $_SESSION["email"]; ?></span></h5>
  <?php } else { ?>
    <h2>Welcome back <?php echo $_SESSION["name"] ?>!!!</h2>
	<h5>Your email id is: <span style="text-decoration:underline;"><?php echo $_SESSION["email"]; ?></span></h5>
  <?php } ?>
  
  <div>
    <a href="<?php echo LOGOUT_URL; ?>">
      Logout
    </a>
  </div>
</div>

Create logout.php function

<?php
session_start();

$_SESSION = array();
unset($_SESSION);
session_destroy();
header("location:index.php");
?>

That’s it Enjoy the code.

Simple Table sorting in jquery with mysql data

Nowadays, We showed our data in Frid view web content for the client. so for every content we need to use Sorting for Client and also our benefits, But Sorting, searching, pagination is not a easy job in HTML tables with Php and mysql data. So many grid view framework out there, Here we Learn about table sorting in jquery.
DataTable.js is the most popular nowadays. Using jquery and mysql structure we are going to create very simple and easy table sorting functions.

Column sorting is a feature where user can sort the results either in ascending or descending order.

Demo                                                                 Download

Step1 : Setup your database and table in MySQL
Before you run this script make sure you have created a database and table in MySQL. Below is the sample sql command to create a database, table, and insert some dummy rows.

CREATE TABLE IF NOT EXISTS `exam` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `student` varchar(55) DEFAULT NULL,
  `subject` varchar(255) DEFAULT NULL,
  `mark` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=17 ;

--
-- Dumping data for table `exam`
--

INSERT INTO `exam` (`id`, `student`, `subject`, `mark`) VALUES
(1, 'John', 'English', 75),
(2, 'John', 'Maths', 85),
(3, 'John', 'Physics', 73),
(4, 'John', 'Chemistry', 80),
(5, 'robert', 'English', 60),
(6, 'robert', 'Maths', 65),
(7, 'robert', 'Physics', 69),
(8, 'robert', 'Chemistry', 70),
(9, 'Adam', 'English', 75),
(10, 'Adam', 'Maths', 70),
(11, 'Adam', 'Physics', 85),
(12, 'Adam', 'Chemistry', 77),
(13, 'jack', 'English', 95),
(14, 'jack', 'Maths', 90),
(15, 'jack', 'Physics', 91),
(16, 'jack', 'Chemistry', 75);

For connect database Check this

Step 2: Fetch records from table and display
Now the next step is simple, fetch all records from MySQL table and display.

<body>
<table id='table_sort' class='tablesorter'>
<thead>
<tr>
<th>id</th>
<th>student</th>
<th>subject</th>
<th>mark</th>
</tr>
</thead>
<tbody>
<?php
//connect to database
include "../config.php";

//query the database
$sql = "select * from exam";
$rs = mysql_query ( $sql );
while ( $row = mysql_fetch_array ( $rs ) ){   // fetch the data from database
extract ( $row );   // use function to get exact row asc or desc
	?>
<tr>
<td><?php echo $id; ?></td>


<td><?php echo $subject; ?></td>
<td><?php echo $subject; ?></td>
<td><?php echo $mark; ?></td>

</tr>
<?php
}
?>
</tbody>
</table>

Step 3: Include jquery functions for sorting

<!-- include jQuery library and table sorter plugin -->
<script type='text/javascript' src='js/jquery-latest.js'>
</script>
<script type='text/javascript' src='js/jquery.tablesorter.min.js'>
</script>


<script type='text/javascript'>
	$(document).ready(function() { 
		$("#table_sort").tablesorter({ 
			//for example we want to disable the 
			//password column (5th column) from sorting
			//we will specify '4' since it was indexed
			//(count starts at '0')
			//and set its property to 'false'
			headers: { 
				4: {    
					sorter: false 
				}
			}
		}); 
	});
</script>

Step 4 : Add css style for design

.tablesorter {
margin:0px;
padding:0px;
width:100%;	
box-shadow: 10px 10px 5px #888888;

-moz-border-radius-bottomleft:0px;
-webkit-border-bottom-left-radius:0px;
border-bottom-left-radius:0px;

-moz-border-radius-bottomright:0px;
-webkit-border-bottom-right-radius:0px;
border-bottom-right-radius:0px;

-moz-border-radius-topright:0px;
-webkit-border-top-right-radius:0px;
border-top-right-radius:0px;

-moz-border-radius-topleft:0px;
-webkit-border-top-left-radius:0px;
border-top-left-radius:0px;
}

.tablesorter table{
width:100%;
margin:0px;
padding:0px;
}


.tablesorter tr:nth-child(odd){ 

background-color:#D9ECFE; 

}
.tablesorter tr:nth-child(even)    { background-color:#ffffff; }
.tablesorter td{
vertical-align:middle;
text-align:left;
padding:7px;
font-size:16px;
font-family:arial;
font-weight:normal;
color:#000000;
}

table.tablesorter thead tr .header {
    background-image: url(images/bg.gif);
    background-repeat: no-repeat;
    background-position: center right;
    cursor: pointer;
}

table.tablesorter thead tr .headerSortDown {
    background-image: url(images/desc.gif);
}
table.tablesorter thead tr .headerSortUp {
    background-image: url(images/asc.gif);
}

construct the table with id ‘table_srot’ and use this id for sorting. thead tag is required for using tablesorter. tbody tag is also required for using tablesorter. using mysql fetching with array you can get the data and using “exact” function you can access exect row asc or dec.
That’s it enjoy the code.