Friday, November 11, 2016

How to implement Oauth 2.0 [bshaffer] in Laravel framework

6:23:00 PM 0
Install the OAuth2 server and HTTP Foundation bridge dependencies using Composer:
  • composer require bshaffer/oauth2-server-php and
  • composer require bshaffer/oauth2-server-httpfoundation-bridge
Setup your database and run the provided migration Download migration from the link given below and add it in database.( https://github.com/julien-c/laravel-oauth2-server/commit/b290d4f699b9758696444e2d62dd82f0eeedcb7d) (php artisan db:migrate)

Seed your database using the provided script : Download test database contents from the link given below and add it in tables. (https://github.com/julien-c/laravel-oauth2-server/commit/8895c54cbf8ea8ba78aafab53a5a0409ce2f1ba2 ) (php artisan db:seed)

Setup your OAuth2 server: To be able to access the single instance anywhere in your Laravel app, you can attach it as a singleton:
  • Add the code give below in App Service Provider file. ( app->providers->AppServiceProvider.php ) or create a new service provider and add it.
public function register()
{
     App::singleton('oauth2', function()
     {
          $storage = new OAuth2\Storage\Pdo(array('dsn' => 'mysql:dbname=laravel_test;host=localhost', 'username' => 'root', 'password' => ''));
          $server = new OAuth2\Server($storage);

          $server->addGrantType(new OAuth2\GrantType\ClientCredentials($storage));
          $server->addGrantType(new OAuth2\GrantType\UserCredentials($storage));
          $server->addGrantType(new OAuth2\GrantType\RefreshToken($storage));

     return $server;
     });
}} 
To generate & regenerate token :
  • Add the code give below in routes file
Route::post('oauth/token', function()
{
    $bridgedRequest  = OAuth2\HttpFoundationBridge\Request::createFromRequest(Request::instance());
    $bridgedResponse = new OAuth2\HttpFoundationBridge\Response();
  
    $bridgedResponse = App::make('oauth2')->handleTokenRequest($bridgedRequest, $bridgedResponse);
  
    return $bridgedResponse;
});
Parameters used to generate token:

URL : http://localhost:8000/api/oauth/token

Headers Parameters:
  • Authorization → Basic dGVzdGNsaWVudDp0ZXN0cGFzcw== [ Basic base64_encode(client_id:client_password) ]
Body Parameters:
  • grant_type → password
  • username → user's name
  • password → user's password
Sample Result :
{
"access_token": "9cf3edc9f6d7437712a0f344872b04641eb336eb",
"expires_in": 3600,
"token_type": "Bearer",
"scope": null,
"refresh_token": "5d975d306fb0c28813caf2c79916890a2f4dbfe4"
}

Parameters used to re-generate token:

URL : http://localhost:8000/api/oauth/token

Headers Parameters:
  • Authorization → Basic dGVzdGNsaWVudDp0ZXN0cGFzcw== [ Basic base64_encode(client_id:client_password) ]
Body Parameters:
  • grant_type → refresh_token
  • refresh_token → refresh token stored in oauth_refresh_tokens table
Sample Result :
{
"access_token": "205edda287528d136d2ec0be32d8b5e1b572cc77",
"expires_in": 3600,
"token_type": "Bearer",
"scope": null
}

To authenticate token and to get token details (Authentication Server):
  • Add the code give below in routes file
Route::get('private', function()
{
 $bridgedRequest = OAuth2\HttpFoundationBridge\Request::createFromRequest(Request::instance());
 $bridgedResponse = new OAuth2\HttpFoundationBridge\Response();
  
 if (App::make('oauth2')->verifyResourceRequest($bridgedRequest, $bridgedResponse)) {
  
 $token = App::make('oauth2')->getAccessTokenData($bridgedRequest);
  
  return Response::json(array(
   'private' => 'stuff',
   'user_id' => $token['user_id'],
   'client' => $token['client_id'],
   'expires' => $token['expires'],
   ));
 }
 else
 {
  return Response::json(array(
   'error' => $bridgedResponse->getParameter('error'),
   'error_description' => $bridgedResponse->getParameter('error_description'),
   ), $bridgedResponse->getStatusCode());
 }
});

Parameters used to authenticate token:
 
URL :
http://localhost:8000/api/ private


Headers Parameters:
Authorization → Bearer 9b50c978cca15802000beaf13ef95c33e14f1a81 [Bearer Token]
{
"private": "stuff",
"user_id": "bshaffer",
"client": "testclient",
"expires": 1478822036
}

Tuesday, September 20, 2016

Case Sensitive login in codeigniter

7:48:00 PM 0
How to implement case sensitive user login in codeigniter ?. This is the topic we are gonna to see today. Implementing login with case sensitive option in codeigniter is very easy. That is, we need to give 'LIKE BINARY' after the database field name in model query.

Case Sensitive login in codeigniter
Case Sensitive login in codeigniter

Lets see the example codeigniter controller and model codes to that are used to get case sensitive user data from database.

Controller Code:


<?php

function login_controller()
{
 $email = $this->input->post('email');
 $password = $this->input->post('password');
 
 if($email && $password)
 {
  $query = $this->user_model->login_model($email,$password);
  if($query)
  {
   echo "Login Success..";
  }
  else
  {
   echo "Login Failed..";
  }
 }
}
?>

Model Code:

function login_model($email,$password)
{
 $this->db->select('*');
 $this->db->from("user_account");
 $this->db->where("email",$email);
 $this->db->where("password like binary",$password);
 $query = $this->db->get();
 if($query->num_rows() > 0)
 {
  return $query->result();
 }
return false;
}

The main thing used here is $this->db->where("password like binary",$password);

Search Keywords
  • Case sensitive password check in codeigniter
  • Codeigniter case sensitive query
  • Codeigniter Binary query

Jquery copy to clipboard - ctrl + c event

6:59:00 PM 0
Jquery copy to clipboard. How to copy a texbox or textarea content to clipboard using jquery. Here you will get exact result for this question. By using the below code, you can perform "ctrl + c" keyboard event automatically when a user hits a button. Lets see copy to clipboard jquery example
Jquery copy to clipboard - ctrl + c event
Jquery Control + C

Jquery copy to clipboard - ctrl + c code:


<input id="input_textbox" type="text" value="w3schools100" />
<button id="copy_but">Copy to clipboard</button>
 
<script>
    var input = document.getElementById("input_textbox");
 
    $("#copy_but").click(function(event){
        event.preventDefault();
        input.select();
        document.execCommand("copy");
    });
</script>

Search keywords: 
  • How to copy textbox contents using jquery
  • Jquery copy text to clipboard
  • Copy text box contents on a button click
  • How to trigger ctrl + c event  via code

Monday, July 25, 2016

Dim the whole page and show loading image on button click

6:15:00 PM 0
How to grey out or dim the whole page and display loading image on the center of the page, when user clicks a button ?. Most of the programmers uses ajax to request data processing. Some requests may take more time and some will take less time. As they are processing using ajax method, page won't  be refreshed or default loading button in the browser too wont work. So when user clicks a button, and if the request is in progress, we have to display a loading image to notify the users that request is in progress.

show loading image on button click
Show loading image on button click

To implement this loading image feature in your project copy the codes given below and use it in appropriate places.


/* Absolute Center Spinner */
.loading {
  position: fixed;
  z-index: 999;
  height: 2em;
  width: 2em;
  overflow: show;
  margin: auto;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
}
 
/* Transparent Overlay */
.loading:before {
  content: '';
  display: block;
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0,0,0,0.2);
}
 
/* :not(:required) hides these rules from IE9 and below */
.loading:not(:required) {
  /* hide "loading..." text */
  font: 0/0 a;
  color: transparent;
  text-shadow: none;
  background-color: transparent;
  border: 0;
}
 
.loading:not(:required):after {
  content: '';
  display: block;
  font-size: 10px;
  width: 1em;
  height: 1em;
  margin-top: -0.5em;
  -webkit-animation: spinner 1500ms infinite linear;
  -moz-animation: spinner 1500ms infinite linear;
  -ms-animation: spinner 1500ms infinite linear;
  -o-animation: spinner 1500ms infinite linear;
  animation: spinner 1500ms infinite linear;
  border-radius: 0.5em;
  -webkit-box-shadow: rgba(0, 0, 0, 0.75) 1.5em 0 0 0, rgba(0, 0, 0, 0.75) 1.1em 1.1em 0 0, rgba(0, 0, 0, 0.75) 0 1.5em 0 0, rgba(0, 0, 0, 0.75) -1.1em 1.1em 0 0, rgba(0, 0, 0, 0.5) -1.5em 0 0 0, rgba(0, 0, 0, 0.5) -1.1em -1.1em 0 0, rgba(0, 0, 0, 0.75) 0 -1.5em 0 0, rgba(0, 0, 0, 0.75) 1.1em -1.1em 0 0;
  box-shadow: rgba(0, 0, 0, 0.75) 1.5em 0 0 0, rgba(0, 0, 0, 0.75) 1.1em 1.1em 0 0, rgba(0, 0, 0, 0.75) 0 1.5em 0 0, rgba(0, 0, 0, 0.75) -1.1em 1.1em 0 0, rgba(0, 0, 0, 0.75) -1.5em 0 0 0, rgba(0, 0, 0, 0.75) -1.1em -1.1em 0 0, rgba(0, 0, 0, 0.75) 0 -1.5em 0 0, rgba(0, 0, 0, 0.75) 1.1em -1.1em 0 0;
}
 
/* Animation */
 
@-webkit-keyframes spinner {
  0% {
    -webkit-transform: rotate(0deg);
    -moz-transform: rotate(0deg);
    -ms-transform: rotate(0deg);
    -o-transform: rotate(0deg);
    transform: rotate(0deg);
  }
  100% {
    -webkit-transform: rotate(360deg);
    -moz-transform: rotate(360deg);
    -ms-transform: rotate(360deg);
    -o-transform: rotate(360deg);
    transform: rotate(360deg);
  }
}
@-moz-keyframes spinner {
  0% {
    -webkit-transform: rotate(0deg);
    -moz-transform: rotate(0deg);
    -ms-transform: rotate(0deg);
    -o-transform: rotate(0deg);
    transform: rotate(0deg);
  }
  100% {
    -webkit-transform: rotate(360deg);
    -moz-transform: rotate(360deg);
    -ms-transform: rotate(360deg);
    -o-transform: rotate(360deg);
    transform: rotate(360deg);
  }
}
@-o-keyframes spinner {
  0% {
    -webkit-transform: rotate(0deg);
    -moz-transform: rotate(0deg);
    -ms-transform: rotate(0deg);
    -o-transform: rotate(0deg);
    transform: rotate(0deg);
  }
  100% {
    -webkit-transform: rotate(360deg);
    -moz-transform: rotate(360deg);
    -ms-transform: rotate(360deg);
    -o-transform: rotate(360deg);
    transform: rotate(360deg);
  }
}
@keyframes spinner {
  0% {
    -webkit-transform: rotate(0deg);
    -moz-transform: rotate(0deg);
    -ms-transform: rotate(0deg);
    -o-transform: rotate(0deg);
    transform: rotate(0deg);
  }
  100% {
    -webkit-transform: rotate(360deg);
    -moz-transform: rotate(360deg);
    -ms-transform: rotate(360deg);
    -o-transform: rotate(360deg);
    transform: rotate(360deg);
  }
}

/* The Modal (background) */
.modal {
    display: none; /* Hidden by default */
    position: fixed; /* Stay in place */
    z-index: 1; /* Sit on top */
    padding-top: 100px; /* Location of the box */
    left: 0;
    top: 0;
    width: 100%; /* Full width */
    height: 100%; /* Full height */
    overflow: auto; /* Enable scroll if needed */
    background-color: rgb(0,0,0); /* Fallback color */
    background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
}

/* Modal Content */
.modal-content {
    background-color: #fefefe;
    margin: auto;
    padding: 20px;
    border: 1px solid #888;
    width: 80%;
}

/* The Close Button */
.close {
    color: #aaaaaa;
    float: right;
    font-size: 28px;
    font-weight: bold;
}

.close:hover,
.close:focus {
    color: #000;
    text-decoration: none;
    cursor: pointer;
}
</style>
 
<span id="spinner"></span>
 
<script>
function spinner()
{
$("#spinner").html("<div class='loading'>Loading…</div>");
// To stop spinner, $("#spinner").html("");
}
</script>
 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
 
<button onclick="spinner()">Test Spinner</button>

(Press F5 to stop the spinner..)

Wednesday, July 13, 2016

How to send emails with HTML page/template in codeigniter

5:07:00 PM 0
Codeigniter allows programmers to send HTML file as an email. This helps to send emails using codeigniter in a good formatted and stylish method. Below we have given codes to send HTML pages along with email in codeigniter. Just run it and comment your view below.
codeigniter send email using html template
codeigniter send email using html template

How send emails in codeignter using email templates?

Controller:

public function test_email()
{
        $this->email->set_mailtype("html");
 $this->email->from('noreply@w3schools100.in', 'W3Schools100');
 $this->email->to('receiver@gmail.com');
 $this->email->subject('Subject');
     
 $mail_data['subject'] = 'Email Subject';
 $mail_data['description'] = "Email body contents..Here you can use HTML tables to format your data..And use \n to print date in a new line"

 $message = $this->load->view('email_page', $mail_data, true);
 $this->email->message($message);
 $this->email->send();
} 
View: -> email_page.php

<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"></link>
  <style>
    /* Remove the navbar's default rounded borders and increase the bottom margin */ 
    .navbar {
      margin-bottom: 50px;
      border-radius: 0;
    }
    
    /* Remove the jumbotron's default bottom margin */ 
     .jumbotron {
      margin-bottom: 0;
    }
   
    /* Add a gray background color and some padding to the footer */
    footer {
    background-color: #37454D;
    color:#fff;
      padding: 10px;
    }
  </style>

  <div style="background-color:lightgrey" class="text-center">
  <!-- Give full URL -->
  <img src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgx53RKF84Qif07L__NTVulVu26pHAP9ZSK4wrLupufXv_1rhtzzfjJOFA79ZiM-dLoe6HRtY2gFl9v5UkKJ9UlynyLJTwmRlGBG6PfyJH-O4qoYc2xlp5vCTFeUQoTrv2kYDuv6LXovUNZ/s1600/SB100+copy.png" class="img-responsive" alt="StudentsBlog100" title="Studentsblog100"/>
  </div>

<div class="container">    
  <div class="row">
    <div class="col-sm-12">
     <h3 style="font-weight:bold"><?php if(isset($subject)) { echo $subject; }?></h3>
     <p><?php if(isset($description)) { echo $description; }?></p>
    </div>
  </div>
</div>

<footer class="container-fluid text-center">
  © W3schools100
</footer>
codeigniter send email using html template

  • codeigniter send email html format
  • mail codeigniter 

Friday, June 3, 2016

HOW TO PRINT/ECHO/WRITE ARRAY VALUES IN FILE - PHP

4:25:00 PM 0
Generally it is very easy to write some string in file using php. But some times, we may required to write arrays in file using php. The situation may arise when we required to check API input values, post method values etc..
HOW TO PRINT/ECHO/WRITE ARRAY VALUES IN FILE
Add HOW TO PRINT/ECHO/WRITE ARRAY VALUES IN FILE

General method to write string in php is,
$text = "Hai how are you";
file_put_contents("test.txt",$text);
After executing above code, you will get an output as "Hai how are you" in the file.

How to write array values in a file?

$a = array('1','2','3','4','5');
file_put_contents("test.txt",print_r($a,true));
Execute above code and see the array values printed in the file. If you have any queries or suggestion related this post, feel free to comment below.

Monday, April 11, 2016

How to use or_like and where condition in codeigniter query builder

6:49:00 PM 0
As we know, codeigniter query builder is one of the easiest method to create database queries. But in some complex situations it is not giving exact results. If codeigniter got upgraded, this type of errors will be solved, but it was not upgraded for many years. Anyhow today we are going to see about "How to use or_like and where condition in codeigniter"
or_like and where condition in codeigniter
or_like and where condition in codeigniter

or_like and where condition in codeigniter

Table name : items
idNameTypeCountry
1BananaFruitIndia
2CarrotVegetablePakistan
3AppleFruitUSA
4TomatoVegetableUAE
5OrangeFruitIran
6cucumberVegetableIndia

Consider above table "items". Now you need to search a data from name and country fields, where type =  Fruit. In this case use following code to get exact result from codeigniter.

public function search_items($search_keyword="") {
    $this->db->select('*');
    $this->db->from('items');
    $where = "type = 'Fruit' AND (name LIKE '%$search_keyword%' OR country LIKE '%$search_keyword%')";
    $this->db->where($where);
    $query = $this->db->get();
    if($query->num_rows() > 0) {
        return $query->result();
    }
    return false;
}
Try this and if you have any doubts or any alternative solutions, please comment below. Thank you - W3schools100 Team