php Archives - wiki

Implementing Google Sign-In for Websites java script and PHP

Implementing Google Sign-In for Websites java script and PHP

First step you need to create a google client id

Go to https://console.developers.google.com/project/_/apiui/apis/library

then create a new project or select an existing project

Step.1

create project

Step.2

I am going to create a new project (If you are having a project already you can select that one also)

new project

Step.3

Enable google+ Api

enableing google pluse

enableing google pluse 2

 

Step.4

Choose an Email Address, specify a Product Name, and press Save.

create creadential

In the Credentials tab, select the New credentials drop-down list, and choose OAuth client ID.

create creadential2

Under Application type, select Web application.

create creadential3

 

create creadential4

 

Copy the client id from the google developer console and past it in to the meta tag of the bellow index,html “<YOUR CLIENT ID>”

 

<!DOCTYPE html>
<html>
	<head>
		<meta charset="ISO-8859-1">
		<meta name="google-signin-client_id" content="<YOUR CLIENT ID>"></meta>
		<title>Google login </title>

		<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
	</head>
	
	<body>

		<div id ="signin" class="g-signin2" data-onsuccess="onSignIn"></div>

		<br>Access token<br>
		<textarea id="token" rows="" cols=""></textarea>
		
		<br>
		<button id="verify_in_server">verify in server</button>
		<div id="verify_in_server_result"></div>
		
		<a id ="signout" href="#" onclick="signOut();">Sign out</a>

		<script src="https://apis.google.com/js/platform.js" async defer></script>

		<script type="text/javascript">
		
			/*
			 * Google sign in callback
			 * after loginin to google this function will automatically call
			 * no neet call this function manually
			 */
			function onSignIn(googleUser) {
				var profile = googleUser.getBasicProfile();
	
				var id_token = googleUser.getAuthResponse().id_token;// this token we will send to server to verify
	
				console.log('ID: ' + profile.getId());
				console.log('Name: ' + profile.getName());
				console.log('Image URL: ' + profile.getImageUrl());
				console.log('Email: ' + profile.getEmail());
	
				console.log('Token: ' + id_token);
	
				$("#token").text(id_token);
			}

			function signOut() {
	
				var auth2 = gapi.auth2.getAuthInstance();
				auth2.signOut().then(function() {
					console.log('User signed out.');
				});
			}
			
			$("#verify_in_server").click(function(){
				
				$.ajax({
					type: "POST",
				 	url: "verify.php", 
				 	data: { token: $("#token").text()},
				 	success: function(result){
				    	    $("#verify_in_server_result").html(result);
				   	}
				});
			});

		</script>
	</body>
</html>

 

Server side verification (PHP)

<?php

echo "Result from server<br>";

if (isset ( $_REQUEST['token'] ) && $_REQUEST['token'] != '') {
    
    $response = file_get_contents ( 'https://www.googleapis.com/oauth2/v3/tokeninfo?id_token=' . $_REQUEST['token'] );
    
    $response = json_decode ( $response );
    
    echo "<pre>";
    print_r ( $response );
    echo "</pre>";
}
?>

 

Out Put

login1

login2

login3

login4

ref

https://developers.google.com/identity/sign-in/web/sign-in

By bm on June 29, 2016 | html, java script, php | A comment?
Tags: , , ,

PHP replace between

In this snippet I am just creating an useful function to replace string in between two string (including the given string )

The replace between function definition

<?php
/**
 * function for replaceing sting between two string (included these two strings)
 * @param String $str_start <p>start string of search</p>
 * @param String $str_end <p>ending string of search</p>
 * @param String $replace <p>replace with</p>
 * @param String $string <p>source string (the original string we want to perform search)</p>
 * @return String
 */
function replace_between($str_start, $str_end,  $replace, $source_string) {
    
    $startPos = strpos($source_string, $str_start);
    $endPos = strpos($source_string, $str_end);
    
    if ($startPos === false || $endPos === false) {
        return $source_string;
    }

    $textToDelete = substr($source_string, $startPos, ($endPos + strlen($str_end)) - $startPos);

    return str_replace($textToDelete, $replace, $source_string);
}

?>

sample function calls

sample 1

$mystring = '<div>a b c d e f g a x c </div>';

$new_str = replace_between('a', 'c',  'W', $mystring);

echo $new_str;

Output

<div>W d e f g a x c </div>

 

sample 2

$mystring = '<div>some text <a href="http://workassis.com">click me</a> </div>';

$new_str = replace_between('<a', '</a>',  '', $mystring);

echo $new_str;

Output

<div>some text  </div>

Using preg_replace()

$mystring = '<div>abc def gaxc hiks dfess ddfsdfed </div>';

$new_str = preg_replace('/def[\s\S]+?dfess/', '', $mystring);

echo $new_str;

Output

<div>abc  ddfsdfed </div>

 

ref: http://php.net/manual/en/function.strpos.php,

http://php.net/manual/en/function.substr.php,

http://php.net/manual/en/function.str-replace.php

ref: http://php.net/manual/en/function.preg-replace.php

By bm on June 24, 2016 | php | A comment?
Tags: , ,

Database class

<?php
class databse 
{
     var $host="localhost";
     var $username="root";
     var $password="";
     var $database="testdb";
     var $prefix="";
     public $con;

	function __construct($host = NULL, $username = NULL, $password = NULL, $database = NULL, $prefix = NULL) 
	{
		$this->hostname = ! empty ( $host ) ? $host : $this->host;
		$this->username = ! empty ( $username ) ? $username : $this->username;
		$this->password = ! empty ( $password ) ? $password : $this->password;
		$this->database = ! empty ( $database ) ? $database : $this->database;
		$this->prefix = ! empty ( $prefix ) ? $prefix : $this->prefix;
		$this->con = mysqli_connect ( $this->host, $this->username, $this->password, $this->database ) or die ( 'Error connecting to DB' );
	}

	public function query($sql) 
	{ 
          return mysqli_query($this->con, $sql) or die ( 'Error:' . mysqli_error ( $this->con ) . ', query: ' . $sql );
	}

	public function fetch($sql) 
	{
		$array = mysqli_fetch_array ( $this->query ( $sql ) );
		return $array;
	}

	public function insert($data, $table)
	{

		mysqli_query( $this->con,"INSERT INTO ".$table." (".$fields.") VALUES (".$vals.")");		
	}

	public function update($data, $table)
	{
		mysqli_query($this->con,"UPDATE ".$table." SET age=36 WHERE id=1");
	}

	public function delete($data, $table)
	{
		mysqli_query($this->con,"DELETE FROM ".$table." WHERE age=36");
	}

	public function close() 
	{
		return mysqli_close ( $this->con );
	}

	function __destruct() 
	{
		$this->close ();
	}
}

$db=new databse();

?>

 

By bm on October 7, 2013 | php oop | A comment?
Tags: ,