Sunday, 19 April 2020

Jwt authentication in laravel

Jwt authentication in Laravel 5.5 or above

Step 1#: Run the following three command one by one to install the Jwt in your installed Laravel framework.

composer require tymon/jwt-auth
php artisan vendor:publish --provider="Tymon\JWTAuth\Providers\LaravelServiceProvider"
php artisan jwt:secret


Step 2#: Update your user model

<?php

namespace App;

use Tymon\JWTAuth\Contracts\JWTSubject;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable implements JWTSubject
{
    use Notifiable;

 
    public function getJWTIdentifier()
    {
        return $this->getKey();
    }

   
    public function getJWTCustomClaims()
    {
        return [];
    }

}

Step 3#: Create Auth controller by running this command

php artisan make:controller AuthController
php artisan make:middleware authJwt

add this code to kernel.php

protected $routeMiddleware = [
  ........
'jwt-auth' => \App\Http\Middleware\authJwt::Class,

]

and add the following code to your authcontroller

<?php


namespace App\Http\Controllers; use Illuminate\Support\Facades\Auth; use App\Http\Controllers\Controller; class AuthController extends Controller { public function __construct() { $this->middleware('auth:api', ['except' => ['login']]); } public function login() { $credentials = request(['email', 'password']); if (! $token = auth()->attempt($credentials)) { return response()->json(['error' => 'Unauthorized'], 401); } return $this->respondWithToken($token); } public function me() {

try { $user = auth()->userOrFail(); } catch (\Tymon\JWTAuth\Exceptions\UserNotDefinedException $e) {
return response()->json(['error' => $e->getMessage()], 401);
} return response()->json(auth()->user()); } public function logout() { auth()->logout(); return response()->json(['message' => 'Successfully logged out']); } public function refresh() {
try { $user = auth()->userOrFail(); } catch (\Tymon\JWTAuth\Exceptions\UserNotDefinedException $e) {
return response()->json(['error' => $e->getMessage()], 401);
}
return $this->respondWithToken(auth()->refresh()); } protected function respondWithToken($token) { return response()->json([ 'access_token' => $token, 'token_type' => 'bearer', 'expires_in' => auth()->factory()->getTTL() * 60 ]); } }
?>

Step 4#: Create api routes in api.php file.

<?php

Route::group([
'middleware' => 'api', 'prefix' => 'auth' ], function ($router) {
Route::post('login', 'AuthController@login');
Route::get('logout', 'AuthController@logout');
Route::get('refresh', 'AuthController@refresh'); Route::get('me', 'AuthController@me'); });


?>

Step 5#: Test on postman




Wednesday, 8 April 2020

Mailingboss api integration (Builderall)

Mailingboss api integration

Get Api token after login to builderall acount then mailingboss integration section.

We can integrate these given api in PHP or jquery ajax


1) Get list api from Mailingboss autoresponder Email

Request example


GET: https://member.mailingboss.com/integration/index.php/lists/{api-token} 

Response example JSON:

 {
status: "success",
data: [{
list_uid: "m07ug174cie26",
name: "E-mail Marketing",
display_name: "E-mail Marketing",
description: "E-mail Marketing"
}, {
list_uid: "mj546z2pwp2de",
name: "Lista Teste",
display_name: "Lista Teste",
description: "Lista" 
                  }
                    ]
}

2) Add lead to list api example of Mailingboss autoresponder Email


Request example 


POST: https://member.mailingboss.com/integration/index.php/lists/subscribers/create/{api-token}

PARAMS:
email: teste@teste.com 
                list_uid: vh485p76so057 
                status:confirmed 

Response example JSON: 

{
       status: "success",
      data: {
             subscriber_uid: "ow305e5oat103",
             email: "teste@teste.com",
             taginternals: "testetag, tag2",
             status: "confirmed"
            }

}

Mailingboss is the one of the best module of builderall
If you need any help please feel free to comment. 

Sunday, 2 February 2020

Host '*.wpxhosting.com' is not allowed to connect to this MariaDB server error 1130

Host '*.wpxhosting.com' is not allowed to connect to this MariaDB server

wpxhosting MariaDB server error 1130

When you add database users to the database in WPXhosting and you also assign the password to the user
But while making connection to database  use the password as shown in above image under FTP/MYSQL Login details section. In short username will be different but password same for all database.
Thanks.
 

Wednesday, 25 December 2019

json encode chinese character php

json encode chinese character php

-------json_encode() in PHP returns Chinese characters in escaped-------

Many time you were not able to create php json_encode from special characters which generate the  null. I have a code by which you can create a valid json in php 


//****************start encodeing***********/
$data  = array(
array('Sr No'=> 1,'name' => "删除一个连续数组值的方式产生的非连续数组"),
array('Sr No'=> 2,'name' => "删除一个连续数组值的方式产生的非连续数组"),
array('Sr No'=> 3,'name' => "删除一个连续数组值的方式产生的非连续数组")
);


foreach ($data as $key => $value) {
$data[$key]['name'] = mb_convert_encoding($value['name'], "UTF-8", "UTF-8");
}
echo json_encode($data);

///*************end ********************//

using  mb_convert_encoding($string, "UTF-8", "UTF-8");
function you can easily create a valid jSon 

// ************output is given below ***********//
php json_encode special characters null solved

Method 2:  Change collation to utf8mb4_unicode_ci In mysql DB of your column.

Thanks for sharing your time. I believe that you issue has been resolved Please Give a comment to support my efforts. Thanks 





Saturday, 31 August 2019

send message from popup to content script in chrome extension

send message from popup to content script in chrome extension

You really need this to create chrome extensions for websites like amazon, facebook, flipkart etc..
Step 1: Set permissions to all tabs in manifest file of chrome extension.

"permissions": [
        "activeTab",
          "tabs"
    ],

Step 2: Add this code to popup.js file to send message to content.

  chrome.tabs.query({
                    active: true,
                    currentWindow: true
                }, function (tabs) {
                    chrome.tabs.sendMessage(tabs[0].id,{'action':'frompopup'});
                });


Step 3: Add this code to content.js file

chrome.extension.onMessage.addListener(function(message, sender, send_response) {
    if (message.action== 'frompopup') {
      ////////// do your work here
    }
});

In this way we can send messages.
Thanks for  reading.

send message from content script to background script in chrome extension

send message from Content script to background script in chrome extension

You really need this to create chrome extensions for websites like amazon, facebook, flipkart etc..
Step 1: Set permissions to all tabs in manifest file of chrome extension.

"permissions": [
        "activeTab",
          "tabs"
    ],

Step 2: Add this code to contentscript.js file to send message to background.

chrome.runtime.sendMessage({'type': 'fromcontent'});

Step 3: Add this code to background.js file

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {  
    if (request.type == 'fromcontent') {
               ///////// do your work here
           }
});

In this way we can send messages.
Thanks for reading.

Friday, 9 August 2019

send message from background script to content script on particular tab

send message from background script to content script on particular tab in chrome extension

You really need this to create chrome extensions for websites like amazon, flipkart, facebook etc..
Step 1: Set permissions to all tabs in manifest file of chrome extension.

"permissions": [
        "activeTab",
          "tabs"
    ],

Step 2: Add this code to contentscript.js file to send message to background.

/// content script is work individually for every tab so we can send message to background

chrome.runtime.sendMessage({'action':'content'});


Step 3: Add this code to background.js file

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {  
   var senderId = sender.tab.id; ///// sender id of particular tab
    if (request.from == 'content') {
               chrome.tabs.sendMessage(senderId,{action:'takeaction',});
           }
});

In this way we can send back message to particular tab by sending sender id.
Thanks reading.

Thursday, 27 June 2019

Interview questions of codeigniter framework

Interview questions of codeigniter framework


Q 1: What is helper function in codeigniter?
Ans: Helper file is a collection of functions in a particular category.A helper can be loaded by
$this->load->helper('name');
Q 2: Define hook.
Ans: It is use to modify the inner workings of the framework without hacking the core files. When CodeIgniter runs it follows a specific execution process e.g. pre_system , pre_controller etc..
Q 3: How to load a custom library in codeigniter?
Ans: $CI =& get_instance(); On $CI object you can load library.
e.g. $CI->load->library('classname');
Q 4: How load automatically a library in codeigniter ?
Ans: write the name of class in autoload file in autoload array. e.g. database
Q 5:What is the name of database object/
Ans: $ob->
Q 6: How we can require a custom library in controller using APPATH?
Ans: require APPPATH . '/libraries/filename.php';
Q 7: Generate a random sting which contains alphabet and numbers having length 15. Ans: For this we can use string helper function.
e.g. random_string('alnum', 16);
Q 8: In which file you can define the modify routes?
Ans: application/config/routes.php
$route['product'] = 'controller_name/function_name'; browser url will be www.example.com/product
Q 9: Which library is used for form validation in codigniter? Ans: Please type in comment box.

Sunday, 19 May 2019

jwt in wordpress

Jwt authentication in wordpress for rest api,

In this tutorial we will learn how we can implement jwt authentication in wordpress for every Rest api request (Not only for private posts.).

Using jwt authentication we can protect your wordpress data post data.

Step: 1. Install and activate the wp rest api plugin. And download the jwt library form github link is given below.


Place this file inside your active theme directory along with functions.php file

comment these few lines as show below:

//namespace Firebase\JWT;
//use \DomainException;
//use \InvalidArgumentException;
//use \UnexpectedValueException;
//use \DateTime;

and save this file with "jwt.php".
Than include this file in function.php using this line of code

require get_template_directory() . '/jwt.php'; 

Step 3: create a page template token.php

as show below:
get jwt token

Hello is the secret key at line no 13.
at line number 6 you can change username or password as you desire.

Step: 4 Put this code inside function.php

decode jwt token data

Get token form headers and decoded the token data using jwt libraray.

Postman testing sample images are given below:


get jwt token passing username and password

Send jwt token with every request to get data:
send jwt token in header data


Thank you for giving yours time.

Saturday, 13 April 2019

create pdf file from caldera form data

Caldera form pdf file

Install Run Action addon  then add a action on process

as shown in fig:
caldera form pdf  

Install dompdf (open source) which using composer inside you theme folder 
Using this command

Composer require dompdf

Than add the following code to yours functions.php file

require_once '/vendor/autoload.php';
 use Dompdf\Dompdf;
add_action('create_pdf','create_pdf_fun');

function create_pdf_fun($data)
{

$html = 'First Name:'.$data['first_name'].'<br>
        Last Name:'.$data['last_name'].'<br>
        Email:'.$data['email_address'].'<br>
        message:'.$data['message'].'<br>
        Question:'.$data['comments_questions'];
// instantiate and use the dompdf class
$dompdf = new Dompdf();
$dompdf->loadHtml($html);

$dompdf->setPaper('A4', 'landscape');
$dompdf->render();

$output = $dompdf->output();

$subdir = wp_get_upload_dir();
$upload_path = 'wp-content/uploads'.$subdir['subdir'].'/'.rand(1,2000).'test.pdf';
file_put_contents($upload_path, $output);
}

Thank you for giving your time!
 

Saturday, 16 March 2019

send caldera form data to api

Send caldera form data to api

How to send a HTTP POST with the form data to another URL

  • Install caldera form run action add on which is free

    Then add post processor as shown in figure 

    Define action name e.g. send_data

    and put this code in function.php as given below


    add_action('send_data','send_data_function');

    function send_data_function($data)
    {

    $url = 'http://localhost/api.php';
    $myvars = array('firstname' =>$data['first_name'], //$data['slug'] change according to your form field slug
                    'lastname' => $data['last_name'],                  'email' => $data['email_address'],
                    'message' => $data['message'],
                    'commentque' => $data['comments_questions']
     );

    $ch = curl_init( $url );
    curl_setopt( $ch, CURLOPT_POST, 1);
    curl_setopt( $ch, CURLOPT_POSTFIELDS, $myvars);
    curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt( $ch, CURLOPT_HEADER, 0);
    curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1);

    curl_exec( $ch );

    }

    In this way we can post the caldera form data  to api in wordpress

 

Saturday, 26 January 2019

Self attested declaration for no family member in Government Job pdf

Self attested declaration for no family member in Government Job pdf

Download pdf Hssc Self-attested declaration for no family member in Government Job

Take print on A-4 size sheet then fill the all particulars

Thanks for visiting.....

Click the below button to
Self-attested declaration for no family member in Government Job

Sunday, 6 January 2019

htet tgt paper downlaod 2019 pdf

Htet previous year tgt paper download.

This paper was held in 05-Jan-2019.

Thanks for visiting.....

Click the below button to download paper.

Thursday, 8 November 2018

Jwt in php codeigniter framework

Jwt in php Codeigniter framework, My internet connection is  Airtel

Follow the steps as shown in given video

 



In controller Test.php


<?php
require APPPATH . '/libraries/ImplementJwt.php';

class Test extends CI_Controller
{
    public function __construct()
    {
        parent::__construct();
        $this->objOfJwt = new ImplementJwt();
        header('Content-Type: application/json');
    }

    /////////// Generating Token and put user data into  token ///////////

    public function LoginToken()
    {
            $tokenData['uniqueId'] = '55555';
            $tokenData['role'] = 'admin';
            $tokenData['timeStamp'] = Date('Y-m-d h:i:s');
            $jwtToken = $this->objOfJwt->GenerateToken($tokenData);
            echo json_encode(array('Token'=>$jwtToken));
         }
    
    //////// get data from token ////////////
        
    public function GetTokenData()
    {
    $received_Token = $this->input->request_headers('Authorization');
        try
            {
            $jwtData = $this->objOfJwt->DecodeToken($received_Token['Token']);
            echo json_encode($jwtData);
            }
            catch (Exception $e)
            {
            http_response_code('401');
            echo json_encode(array( "status" => false, "message" => $e->getMessage()));exit;
            }
    }
}

 

Step 2: ImplementJwt.php

 <?php
require APPPATH . '/libraries/JWT.php';


class ImplementJwt
{
  

    //////////The function generate token/////////////
    PRIVATE $key = "subcribe_my_channel"; // url: https://www.youtube.com/watch?v=zD4IGp1lBWs
    public function GenerateToken($data)
    {         
        $jwt = JWT::encode($data, $this->key);
        return $jwt;
    }
   


   //////This function decode the token////////////////////
    public function DecodeToken($token)
    {         
        $decoded = JWT::decode($token, $this->key, array('HS256'));
        $decodedData = (array) $decoded;
        return $decodedData;
    }
}
?> 

Download  jwt library: 


https://github.com/firebase/php-jwt

To check jwt token data:


https://jwt.io/

 

 

Friday, 25 May 2018

paytm gateway integration in codeigniter

paytm gateway integration in codeigniter

How we can integrate paytm gateway in codeigniter framework

Step 1: Downlaod the paytm gateway library form the github

https://github.com/Paytm-Payments/Paytm_Web_Sample_Kit_PHP

You can follow this video for placing paytm lib files in codeigniter framework



In controller

<?php

require_once(APPPATH."libraries/lib/config_paytm.php");
require_once(APPPATH."libraries/lib/encdec_paytm.php");


class Welcome extends CI_Controller {

    public function PaytmGateway()
    {
        $orderId = 106; /// must be unique
      $this->StartPayment($orderId);
    }

    public function StartPayment($orderId)
    {
        $paramList["MID"] = PAYTM_MERCHANT_MID;
        $paramList["ORDER_ID"] = $orderId;     
        $paramList["CUST_ID"] = 344;   /// according to your logic
        $paramList["INDUSTRY_TYPE_ID"] = 'RETIAL';
        $paramList["CHANNEL_ID"] = 'WEB';
        $paramList["TXN_AMOUNT"] = 50;
        $paramList["WEBSITE"] = PAYTM_MERCHANT_WEBSITE;
   
        $paramList["CALLBACK_URL"] = "http://127.0.0.1/gateway/Welcome/PaytmResponse";
        $paramList["MSISDN"] = '77777777'; //Mobile number of customer
        $paramList["EMAIL"] ='foo@gmail.com';
        $paramList["VERIFIED_BY"] = "EMAIL"; //
        $paramList["IS_USER_VERIFIED"] = "YES"; //
      //  print_r($paramList);
        $checkSum = getChecksumFromArray($paramList,PAYTM_MERCHANT_KEY);

        ?>

        <!--submit form to payment gateway OR in api environment you can pass this form data-->
   
        <form id="myForm" action="<?php echo PAYTM_TXN_URL ?>" method="post">
        <?php
         foreach ($paramList as $a => $b) {
        echo '<input type="hidden" name="'.htmlentities($a).'" value="'.htmlentities($b).'">';
       }
       ?>
            <input type="hidden" name="CHECKSUMHASH" value="<?php echo $checkSum ?>">
        </form>
        <script type="text/javascript">
            document.getElementById('myForm').submit();
         </script>
 
<?php
    }

    /////////// response from paytm gateway////////////
    public function PaytmResponse()
    {
        $paytmChecksum = "";
        $paramList = array();
        $isValidChecksum = "FALSE";

        $paramList = $_POST;
        echo "<pre>";
        print_r($paramList);
   
//        $paytmChecksum = isset($_POST["CHECKSUMHASH"]) ? $_POST["CHECKSUMHASH"] : ""; //Sent by Paytm pg
//
//        $isValidChecksum = verifychecksum_e($paramList, PAYTM_MERCHANT_KEY, $paytmChecksum); //will return TRUE or FALSE string.
//
//        if($isValidChecksum == "TRUE")
//        {
//            if ($_POST["STATUS"] == "TXN_SUCCESS")
//            { /// put your to save into the database // tansaction successfull
//                var_dump($paramList);
//            }
//            else {/// failed
//                var_dump($paramList);
//            }
//        }else
//        {//////////////suspicious
//           // put your code here
//       
//        }
    }
}
?>

Do not forget to subscribe my channel if this code help you

Thursday, 19 April 2018

PHP codeigniter status code in not working

While making project in Codeigniter framework many developers face these problems:
  • php http_response_code not working 
  • Http response code always returns 200
  • php http_response_code not working when hosting a linux server
  • 404 page not found in not working
  • php 500 not working in codeigniter
  • header already sent error in php
  • warning cannot modify header information headers already sent by (output started xyz.php line no...

All these problems occur when you host your website at Linux server that you have developed in codeigniter framework. 

You have to modify index.php file which is in the root directory of Codeigniter framework.

Step 1) Add ob_start(); function at the beginning of index.php after <?php

This function will turn on the output buffering. so that http response code works correctly. 

Step 2) define('ENVIRONMENT','development');

The modified index.php file is as


Thanks for sharing your valuable time.......