Integrate ICICI EazyPay payment gateway to your website

In this tutorial I would like to explain how to integrate Eazypay into your website.I am using Codeigniter to integrate eazypay.

Register and get you Merchant details through registration in ICICI Eazypay

To encrypt all parameter you can use eazypay inbuilt function of encryption.Please find below the code

function eazypayu_aes128Encrypt($plaintext,$key){
      $cipher = "AES-128-ECB";   
      if (in_array($cipher, openssl_get_cipher_methods())){
       $ivlen = openssl_cipher_iv_length($cipher);
       $iv = openssl_random_pseudo_bytes($ivlen);
       $ciphertext = openssl_encrypt($plaintext, $cipher, $key, $options=0, $iv);
       return $ciphertext;
      }
}

To process your payment you have to take input from user and after thet serialize all data and set as parameter value.Below code is for reference.

public function make_payment() {
	$amount = $this->input->post('amount');
	$merchant_id = "YOUR MERCHANT ID";
	$key = "YOUR MERCHANT KEY";
	$reference_no = 2; 
	$sub_merchant_id = "YOUR SUBMERCHANT ID";
	$return_url = "YOUR REGISTERED RETURN URL";
	$paymode = "9";
	$mandatory_fields = $reference_no ."|".$sub_merchant_id ."|".$amount;
	$opt_fields = "";
	$e_sub_merchant_id = $this->eazypayu_aes128Encrypt($sub_merchant_id, $key);
	$e_reference_no = $this->eazypayu_aes128Encrypt($reference_no, $key);
	$e_amount = $this->eazypayu_aes128Encrypt($amount, $key);
	$e_return_url = $this->eazypayu_aes128Encrypt($return_url, $key);
	$e_paymode = $this->eazypayu_aes128Encrypt($paymode, $key);
	$e_mandatory_fields = $this->eazypayu_aes128Encrypt($mandatory_fields, $key);
	
	$redirect_url = 'https://eazypay.icicibank.com/EazyPG?merchantid='.$merchant_id.'&mandatory fields='.$e_mandatory_fields.'&optional fields='.$opt_fields.'&returnurl='.$e_return_url.'&Reference No='.$e_reference_no.'&submerchantid='.$e_sub_merchant_id.'&transaction amount='.$e_amt.'&paymode='.$e_paymode.'"';		

	redirect($redirect_url );
    		
}

After payment done you have to capture response getting from return URL. Here is the sample code to capture the response.

 public function success(){
        $res = $_REQUEST;
        $data_transaction = array(
        'Response_Code'=> $res['Response_Code'],
        'Unique_Ref_Number'=> $res['Unique_Ref_Number'],
        'Service_Tax_Amount'=> $res['Service_Tax_Amount'],
        'Processing_Fee_Amount'=> $res['Processing_Fee_Amount'],
        'Total_Amount'=> $res['Total_Amount'],
        'Transaction_Amount'=> $res['Transaction_Amount'],
        'Transaction_Date'=> date('Y-m-d',strtotime($res['Transaction_Date'])),
        'Interchange_Value'=> $res['Interchange_Value'],
        'TDR'=> $res['TDR'],
        'Payment_Mode'=> $res['Payment_Mode'],
        'SubMerchantId'=> $res['SubMerchantId'],
        'ReferenceNo'=> $res['ReferenceNo'],
        'ID'=> $res['ID'],
        'RS'=> $res['RS'],
        'TPS'=> $res['TPS'],
        'mandatory_fields'=> $res['mandatory_fields'],
        'optional_fields'=> $res['optional_fields'],
        'RSV'=> $res['Response_Code'],
        '_policy'=> $res['_policy'],
        'visitor'=> $res['visitor']
        );
        
        $this->db->insert('tbl_all_payments', $data_transaction);
        
        $this->load->view('success_page');
        
    }

Thank you for reading this post. we hope you like this Post, Please feel free to comment below, your suggestion. if you face any issue with this code let us know. We’d love to help! Stay tuned!

Amazon SES SMTP in PHPMailer: Send Email Using AWS SES and PHPMailer in CI

With having a large number of features, amazon become a popular hosting service provider. In this tutorial we will see how to send Email using AWS SES and PHPMailer with SMTP Configuration. We will see step by step this implementation.

Get SMTP Credentials from AWS SES:

To get SMTP Credentials from Amazon SES you need to do following simple things:

  • Login to your amazon console account.To login click here Sign in to AWS Account.
  • Go to the Simple Email Service Section(You can search it from search bar by typing Simple Email Service).
  • Select SMTP Settings from left sidebar menu.
  • Click on “Create My SMTP Credential” button to generate SMTP credentials.
  • Copy username and password to use in your application.

Setting up AWS SES SMTP Credentials in PHPMailer:

To use SMTP  in PHPMailer .

$mail->isSMTP();
To set from(Sender) Email Address.
$mail->setFrom('info@techalltype.com', 'Techalltype');
Replace info@techalltype.com with your “From” address. This address must be verified with Amazon SES. You can verify domain name on AWS SES. After verifying you will be able to send email from any email ID which is ended with this domain.
To add recipient address in PHPMailer.
$mail->addAddress('any@techalltype.com', 'Recepient Name');
Replace any@techalltype.com with a “To” address. You can include several address to send email to multiple recipients.
To set AWS SES SMTP user name in PHPMailer.
$mail->Username = 'Your AWS SMTP User Name';
Replace smtp_username with your Amazon SES SMTP user name.
To set AWS SES SMTP Password in PHPMailer.
$mail->Password = 'Your AWS SES SMTP Password';
Replace SMTP password with your Amazon SES SMTP password.
To setup configuration.
$mail->addCustomHeader('X-SES-CONFIGURATION-SET', 'ConfigSet');
If you do not want to use a configuration set, comment or remove above line.
To set Host Name.
$mail->Host = 'email-smtp.us-east-1.amazonaws.com';
If you’re using Amazon SES in a region other than US West (Oregon),         replace email-smtp.us-east-1.amazonaws.com with the Amazon SES SMTP endpoint in the appropriate region.

Setting up PHPMailer Class in Codeigniter Application:

After generating SMTP Credentials now we will see how to Configure PHPMailer Class with AWS SES SMTP Credentials in our Codeigniter Application. To install PHPMailer inside of Codeigniter Application we will use composer.Please find below the command to install PHPMailer using composer.

$ composer require phpmailer/phpmailer

After installing, you will get a vendor folder inside project root folder.

Setup Composer Autoload for PHPMailer Class:

You need to set vendor directory path inside application/config/config.php.

$config['composer_autoload'] = 'vendor/autoload.php';

Creating Controller(Amazon SES SMTP Setup) and Complete Code:

Create a controller named AwsSesSMTPController.php and use PHPMailer class inside controller.Please find below the complete code of controller.

<?php
defined('BASEPATH') OR exit('No direct script access allowed');
use PHPMailer\PHPMailer\PHPMailer;
class Welcome extends CI_Controller {
public function index()
{
$mail = new PHPMailer;
$mail->isSMTP();
$mail->setFrom('info@techalltype.com', 'Techalltype');
$mail->addAddress('any@techalltype.com', 'Recepient Name');
$mail->Username = 'Your AWS SMTP User Name';
$mail->Password = 'Your AWS SES SMTP Password';
$mail->addCustomHeader('X-SES-CONFIGURATION-SET', 'ConfigSet');
$mail->Host = 'email-smtp.us-east-1.amazonaws.com';
$mail->Subject = 'Amazon SES test using PHPMailer';
$mail->isHTML(true);
$mail->Body = '<h1>Email Test</h1> This email was sent through the Amazon SES SMTP interface using the PHPMailer class.';
$mail->SMTPAuth = true;
$mail->SMTPSecure = 'tls';
$mail->Port = 587;

/* The alternative email body; this is only displayed when a recipient
opens the email in a non-HTML email client. The \r\n represents a
line break.*/
$mail->AltBody = "Email Test\r\nThis email was sent through the Amazon SES SMTP interface using the PHPMailer class.";
if(!$mail->send()) {
echo "Email not sent. " , $mail->ErrorInfo , PHP_EOL;
} else {
echo "Email sent!" , PHP_EOL;
}
}
}
Note: If your account is still in the sandbox, this address must be verified. Also note that you can include several addAddress() lines to send email to multiple recipients.
Thank you for reading this post. we hope you like this Post, Please feel free to comment below, your suggestion. if you face any issue with this code let us know. We’d love to help! Stay tuned!

Email using AWS SES: How to Send Email using AWS SES in Codeigniter

In this post I would like to show how to send email using AWS SES(Simple Email Service). Here I will use codeigniter framework to send Email. Lets start with step by step.

You may also like this post How to Send SMS using AWS SNS.

I am assuming that you already know about setup of codeigniter.If you have any issue with codeigniter setup then you can check this post Codeigniter Setup.

Get Client key and Client Secret key from AWS:

Login to your aws console. here you can find the Menu “My Billing Dashboard” under profile area.Inside of Access keys (access key ID and secret access key) you need to create new access key and save it to use in future.

Installation and Configuration AWS SDK in codeigniter:

To setup AWS SDK with codeigniter, need to install AWS SDK using composer. You can get it easily installed.Go to your root folder of the codeigniter application and run Below command.

composer require aws/aws-sdk-php

Creating Controller( Email using AWS SES ):

Next, we are going to create a controller file named AwsSesController.php inside application/controllers where we will put all Email configuration and send email function.Please find below the code.

<?php
defined('BASEPATH') OR exit('No direct script access allowed');
use Aws\Common\Aws;
use Aws\Ses\SesClient;
class AwsSesController extends CI_Controller {
publicfunction __construct()
{
parent::__construct();
}
publicfunction sendEmail(){

$params = array(
'credentials'=> array(
'key'=>'CLIENT KEY',
'secret'=>'CLIENT SECRET KEY',
),
'region'=>'us-east-1',
'version'=>'latest'
);
$SesClient = new SesClient($params);

$sender_email = 'hitesh.maity@gmail.com';
$recipient_emails = ['hitesh.maity@gmail.com'];

// Specify a configuration set. If you do not want to use a configuration comment it or delete.
//$configuration_set = 'ConfigSet';

$subject = 'Test Email From Techalltype';
$plaintext_body = 'This email was sent with Amazon SES using the AWS SDK for PHP.' ;
$html_body = '<h1>Test Email From Techalltype</h1>';
$char_set = 'UTF-8';

try {
$result = $SesClient->sendEmail([
'Destination'=> [
'ToAddresses'=> $recipient_emails,
],
'ReplyToAddresses'=> [$sender_email],
'Source'=> $sender_email,
'Message'=> [
'Body'=> [
'Html'=> [
'Charset'=> $char_set,
'Data'=> $html_body,
],
'Text'=> [
'Charset'=> $char_set,
'Data'=> $plaintext_body,
],
],
'Subject'=> [
'Charset'=> $char_set,
'Data'=> $subject,
],
],
// If you aren't using a configuration set, comment or delete the following line
//'ConfigurationSetName' => $configuration_set,
]);
$messageId = $result['MessageId'];
echo("Email sent! Message ID: $messageId"."\n");
} catch (AwsException $e) {
// output error message if fails
echo $e->getMessage();
echo("The email was not sent. Error message: ".$e->getAwsErrorMessage()."\n");
echo "\n";
}
}
}

Moving Out from AWS SES Sandbox mode:

Above Email addresses must be verified with Amazon SES. By default Your Amazon SES account has “sandbox” access.With sandbox access you can only send email to the Amazon SES mailbox simulator and to email addresses or domains that you have verified. To move out from the sandbox access, you have to request a sending limit increase. After that you will get a reply from AWS Support which is about to how you are now ensuring that your mailing list contains only recipients who specifically signed up to receive email from you. And this question arises by AWS support, if you choose YES for the option (I only send to recipients who have specifically requested my mail).

Do not worry about reply.You just do reply them “Our mailing list contains only recipients who specifically signed up to receive email from us“.

Thank you for reading this post. we hope you like this Post, Please feel free to comment below, your suggestion. if you face any issue with this code let us know. We’d love to help!

Codeigniter File Uploading: Single and Multiple file Uploading with Codeigniter

In this tutorial we will see how file uploading process will be done by using codeigniter file upload class.It is very easy to handle all file uploading processes with codeigniter upload class which comes with various inbuilt configuration.Let see step by step how to achieve this.

Key Features of Codeigniter Uploading Class:

  • Various Inbuilt Settings.
  • File Validations.
  • Easy to configure.

Single file Uploading:

Single file uploading, where you can upload one file at a time.Lets see how to implement single file uploading.

1. Create a view file named upload.php inside  application/views directory.

<!DOCTYPE html>
<html>
<head>
<title>TechAllType</title>
</head>
<body>
<center>
<h4><?php
if(!empty($this->session->flashdata('success'))){
echo $this->session->flashdata('success');
}
if(!empty($this->session->flashdata('error'))){
echo $this->session->flashdata('error');
}
?></h4>
<form method="post" enctype="multipart/form-data" action="<?php echo base_url('<span style="color: #333333;">UploadController</span>/upload_file'); ?>">
<fieldset>
<legend>Personal Info</legend>
<table>
<tr>
<td>Name :</td><td><input type="text" name="name"></td>
</tr>
<tr>
<td>Email :</td><td><input type="text" name="email"></td>
</tr>
<tr>
<td>File :</td><td><input type="file" name="myfile"></td>
</tr>
<tr>
<td><input type="submit" name="upload"></td><td></td>
</tr>
</table>
</fieldset>
</form>
</center>
</body>
</html>

2. After done with the view file, next we need to create a controller. Create a controller file called UploadController.php inside application/controllers directory. Here we will load upload library.You can also load upload library globally inside application/config/autoload.php.

Please find below the controller’s code.

UploadController.php

<?php

class <span style="color: #333333;">UploadController</span> extends CI_Controller{
function __construct(){
parent::__construct();
$this->load->model('UploadModel');
}
public function index(){
$this->load->view('upload');
}
public function upload_file(){
$file_data='';

/* configuration and validations */
$config['upload_path'] = 'uploads/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 100;
$config['max_width'] = 1024;
$config['max_height'] = 768;
$config['file_name'] = $_FILES['myfile']['name'];
$this->load->library('upload', $config);
$this->upload->initialize($config);
if($this->upload->do_upload('myfile')){
$file_data = $this->upload->data();
}
else{
// echo $this->upload->display_errors();
$this->session->set_flashdata('error',$this->upload->display_errors());
redirect('UploadController');
}
$data = array(
'name' => $this->input->post('name'),
'email' => $this->input->post('email'),
'photo' => $file_data['file_name']
);
$this->UploadModel->insert_data($data);
$this->session->set_flashdata('success','Detail has been successfully inserted !');
redirect('UploadController');
}
}
?>

3. Next, You need to create a model. Purpose of create a model is to insert all file detail into database, which is being uploaded.Here is how code looks.

UploadModel.php

<?php
class UploadModel extends CI_Model{
function __construct(){
parent:: __construct();
}
public function insert_data($data){
$this->db->insert('upload',$data);
}
}
?>

Multiple file Uploading:

Multiple file uploading, where you can upload multiple file at a time.Lets see how to implement multiple file uploading.

1. View: MultipleUpload.php

<!DOCTYPE html>
<html>
<head>
<title>TechAllType</title>
</head>
<body>
<center>
<h4><?php
if(!empty($this->session->flashdata('success'))){
echo $this->session->flashdata('success');
}
if(!empty($this->session->flashdata('error'))){
echo $this->session->flashdata('error');
}
?></h4>
<form method="post" enctype="multipart/form-data" action="<?php echo base_url('<span style="color: #333333;">MultipleFileUploadController</span>/upload_file'); ?>">
<fieldset>
<legend>Personal Info</legend>
Gallery Id: <input type="text" name="gallery_id"><br><br>
File : <input type="file" name="myfile[]" multiple="multiple"><br><br>
<input type="submit" name="upload"><br>
</fieldset>
</form>
</center>
</body>
</html>

There is no big difference between single and multiple file input only need to include a multiple attribute with input file type.

2. Controller: MultipleFileUploadController.php

<?php

class MultipleFileUploadController extends CI_Controller{
function __construct(){
parent::__construct();
$this->load->model('MultipleFileUploadModel');
}
public function index(){
$this->load->view('MultipleUpload');
}
public function upload_file(){
$count = count($_FILES['myfile']['name']);
for ($i=0; $i < $count; $i++) {
$_FILES['file']['name'] = $_FILES['myfile']['name'][$i];
$_FILES['file']['type'] = $_FILES['myfile']['type'][$i];
$_FILES['file']['tmp_name'] = $_FILES['myfile']['tmp_name'][$i];
$_FILES['file']['error'] = $_FILES['myfile']['error'][$i];
$_FILES['file']['size'] = $_FILES['myfile']['size'][$i];
$config['upload_path'] = 'uploads/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 100;
$config['max_width'] = 1024;
$config['max_height'] = 768;
$config['file_name'] = $_FILES['myfile']['name'][$i];
$this->load->library('upload', $config);
$this->upload->initialize($config);
$this->upload->do_upload('file');
if($this->upload->do_upload('file')){
$file_data = $this->upload->data();
$data[$i]['gallery_id'] = $this->input->post('gallery_id');
$data[$i]['file_name'] = $file_data['file_name'];
$data[$i]['created_date'] = date('Y-m-d h:i:s');
}else{
$this->session->set_flashdata('error',$this->upload->display_errors());
redirect('MultipleFileUploadController<span style="font-size: 1rem;">'</span><span style="font-size: 1rem;">);</span>

}
}
$this->MultipleFileUploadModel->insert_data($data);
$this->session->set_flashdata('success','details has been successfully inserted !');
redirect('MultipleFileUploadController');
}
}
?>

3. Model: MultipleFileUploadModel

<?php
class MultipleFileUploadModel extends CI_Model{
function __construct(){
parent:: __construct();
}
public function insert_data($data){
$this->db->insert_batch('multiple_file_upload',$data);
}
}
?>

Thank you for reading this post. we hope you like this Post, Please feel free to comment below, your suggestion. if you face any issue with this code let us know. We’d love to help!

AWS SNS with Codeigniter: How to Send SMS Using AWS SNS Services in Codeigniter ?

Send Sms using AWS SNS

Amazon Simple Notification Service (SNS) is an exceedingly accessible, strong secure which enables you to build a serverless application. Serverless application enables you to build and run applications and administrations without considering servers. AWS SNS provides sevices at a very cheap price. You can check here AWS SNS pricing.

This tutorial illustrates how to send SMS using AWS services. Let see step by step how to implement this configuration.

Get Client key and Client Secret key from AWS:

Login to your aws console. here you can find the Menu “My Billing Dashboard” under profile area.Inside of Access keys (access key ID and secret access key) you need to create new access key and save it to use in future.

Installation and Configuration AWS SDK in codeigniter:

To get started, download a specific version of the zip file from https://github.com/aws/aws-sdk-php/releases, unzip it inside application/third_party directory of your codeigniter project.

Creating Base Model for Sending Email:

It is best practice to make a base model to put all send sms functionalities so that in every child model you can extend base model to avoid repetition of code.Create a file called My_Model inside application/core directory and put code below giving.Here is how code looks.

My_Model.php

<?php
require_once APPPATH.'third_party/awsSns/aws-autoloader.php';
class MY_Model extends CI_Model
{
public function SendAwsSms(){
$params = array(
'credentials'=> array(
'key'=>'YOUR API KEY',
'secret'=>'YOUR CLIENT SECRET KEY',
),
'region'=>'us-east-1',
'version'=>'latest'
);
$sns = new \Aws\Sns\SnsClient($params);
$args = array(
"SenderID"=>"SenderName",
"SMSType"=>"Transactional",
"Message"=>"Hello ! This is a test message",
"PhoneNumber"=>"Mobile No",
);
$result = $sns->publish($args);
}
}

Creating Model to Extend Base Model:

Now extend base model that already created.

<?php
  class AwsSnsModel extends My_Model {
     public function __construct() {
  }
}
?>

Creating Controller:

After done with the model, next we need to create controller and here we will load model.From controller we need to call the function that already implemented in base model. Also you can pass parameter like phone number and message to the function.

Create a file named AwsSendSmsController.phpinside application/controller directory. Please find below the code.

<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class AwsSendSmsController extends CI_Controller {
publicfunction __construct(){
parent::__construct();
$this->load->model('AwsSnsModel');
}
    public function index(){
        $this->AwsSnsModel->SendAwsSms();
    }
}
Thank you for reading this post. we hope you like this Post, Please feel free to comment below, your suggestion. if you face any issue with this code let us know. We’d love to help!

.

How to Use Pagination Library in Codeigniter ?

This tutorial illustrates how to use pagination library in codeigniter application.In our project where we have a database with heavy data, pagination plays a key role to show data in a very clean manner and less time execution. Pagination is simply useful to take users in a pages of result. Codeigniter pagination library is very easy to use rather than any extra effort. With the help of this example you can easily use pagination into your codeigniter application.Let see with an example of pagination.

I am assuming that you already know installation of codeigniter.If any problem you having in installation then you can go through this link How to install and setup codeigniter framework.

1.Database table creation

First of all create a database table with the help of below sql. This table will contain lots of data so that we can understand how pagination really works.

CREATE TABLE `tbl_user` (
`id` int(11) NOT&amp;amp;nbsp;NULL ,
`name` varchar(255) NOT NULL,
`mobile` varchar(255) NOT NULL,
`address` varchar(255) NOT NULL,
PRIMARY KEY (ID)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

2.Controller for Pagination configuration

Next, we need to create a controller named UserListController.php inside application/controllers directory where we will load pagination library and put all pagination configuration. Please find below the code.

UserListController.php

<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class UserListController extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->library('Pagination'); /*load pagination library */
$this->load->model('userlistmodel');
}
public function index() {
$total_rows = $this->db->from('tbl_user')->get()->num_rows();
$config = $this->pagination_configuration(base_url("users"), $total_rows, 10, 2, 2, true);
$this->pagination->initialize($config);
$page = ($this->uri->segment(2)) ? $this->uri->segment(2) : 0;
$page_num = $page-1;
$page_num = ($page_num<0)?'0':$page_num;
$page = $page_num*$config["per_page"];
$data["links"] = $this->pagination->create_links();
//Pagination ends

$obj_result = $this->userlistmodel->fetch_data($config["per_page"], $page);
$data['result'] = $obj_result;
$data["total_rows"] = $total_rows;
$this->load->view('userlistview', $data);
return;
}
public function pagination_configuration($base_url, $total_rows, $per_page='10', $uri_segment='2', $num_links='2', $use_page_numbers=TRUE) {
$config = array();
$config["base_url"] = $base_url;
$config["total_rows"] = $total_rows;
$config["per_page"] = $per_page;
$config["uri_segment"] = $uri_segment;
$choice = $total_rows/$per_page;
$config['num_links'] = round($choice);
$config['use_page_numbers'] = $use_page_numbers;
$config['full_tag_open'] = '<ul class="pagination">';
$config['full_tag_close'] = '</ul>';
//First Link
$config['first_link'] = 'First';
$config['first_tag_open'] = '<li>';
$config['first_tag_close'] = '</li>';
//Last Link
$config['last_link'] = 'Last';
$config['last_tag_open'] = '<li>';
$config['last_tag_close'] = '</li>';
//Next Link
$config['next_link'] = 'Next';
$config['next_tag_open'] = '<li>';
$config['next_tag_close'] = '</li>';
//Previous Link
$config['prev_link'] = 'Prev';
$config['prev_tag_open'] = '<li>';
$config['prev_tag_close'] = '</li>';
//Current link
$config['cur_tag_open'] = '<li class="active"><a href="#">';
$config['cur_tag_close'] = '</li></a>';
//Digits Link
$config['num_tag_open'] = '<li>';
$config['num_tag_close'] = '</li>';
return $config;
}
}

Note: You can also load pagination library globally. To load pagination globally, we just need to put pagination inside application/config/autoload.php as i am showing below.

[php]
$autoload[‘libraries’] = array(‘database’,’form_validation’);
[/php]

3. Setting up Model

Next, create a model called UserListModel.php inside application/models where we gonna fetch records of table users.Here is code for model.

UserListModel.php

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class UserListModel extends CI_Model {
public function __construct() {
parent::__construct();
}
// Fetch data according to per_page limit.
public function fetch_data($limit, $page) {
$data = array();
$this->db->limit($limit,$page);
$query = $this->db->get("tbl_user");
if ($query->num_rows() >0) {
foreach ($query->result() as $row) {
$data[] = $row;
}
return $data;
}
returnfalse;
}
}
?>

4. Creating View for Pagination

Next, Create a view called userlistview.php inside application/views directory. And here we will display all data in a tabular format with pagination. Please find below the code for view.

<html>
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<title>Codelgniter pagination</title>
<style>
body {
font-family: 'Raleway', sans-serif;
}
.main
{
width: 1015px;
position: absolute;
top: 10%;
left: 20%;
}
.paginationWrap{text-align:right;}
</style>
</head>
<body>
<section class="content">
<div class="row">
<div class="col-xs-12">
<div class="box">
<div class="box-header">
<h3 class="box-title">All Users</h3>
<!--Pagination-->
<div class="paginationWrap"><?php echo ($result)?$links:'';?></div>
</div>
<div class="box-body table-responsive">
<div class="clearfix text-right"style="padding:10px;">
Total Records: <strong><?php echo $total_rows;?>
</strong></div>
<table id="example2"class="table table-bordered table-hover">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Mobile</th>
<th>Address</th>
</tr>
</thead>
<tbody>
<?php
if($result){
foreach($result as $row){
?>
<tr>
<td valign="middle"><?php echo $row->id; ?></td>
<td valign="middle"><?php echo $row->name;?></td>
<td valign="middle"><?php echo $row->mobile;?></td>
<td valign="middle"><?php echo $row->address;?></td>

<?php
}
}
?>
</tbody>
<tfoot>
</tfoot>
</table>
</div>

<!--Pagination-->
<div class="paginationWrap"><?php echo ($result)?$links:'';?></div>
</div>
</div>
</div>
</section>
</body>
</html>

 5. Routes Configuration:

Configure routes as showing below inside application/config/routes.php file.

$route['users']     = 'userlistcontroller';
$route['users/(:num)']  = 'userlistcontroller/index/$1';

Codeigniter Pagination

Pagination using Codeigniter

Thank you for reading this post. we hope you like this Post, Please feel free to comment below, your suggestion. if you face any issue with this code let us know. We’d love to help!

Tumblr OAuth: Authenticate with tumblr in Codeigniter

In this post I would like to show how can you validate user with tumblr OAuth. Tumblr oauth login API allow to authenticate user into web applications by using their tumblr account. Follow me I will show you step by step how we can achieve this.

1.) Register application:

First of all you need to register your application in tumblr. To get register your app in tumblr Click here. Fill all the details and after that you will get consumer key and secret key that you need to apply in oauth setup.

Register app to get keys from tumblr oauth

2.) Installing tumblr OAuth Library:

Install tumblr oauth library using composer into codeigniter application.

composer require tumblr/tumblr

3.) Setup tumblr oauth in codeigniter:

After successfully registered you will get oauth consumer key and secret key.

Consumer and secret key (Tumblr oauth key)

Now let see how can you setup tumblr oauth. Please find below the controller’s code.

<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class TumblrLoginController extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->library('session');
}
Public function index()
{
$consumerKey = "YOUR_CONSUMER_KEY";
$consumerSecret = "CONSUMER_SECRET KEY";

$client = new Tumblr\API\Client($consumerKey, $consumerSecret);
$requestHandler = $client->getRequestHandler();
$requestHandler->setBaseUrl('https://www.tumblr.com/');

// If user visiting the first time
if (!$_GET['oauth_verifier']) {
// grab the oauth token
$resp = $requestHandler->request('POST', 'oauth/request_token', array());
$out = $result = $resp->body;
$data = array();
parse_str($out, $data);

$oauthData = array(
't' => $data['oauth_token'],
's' => $data['oauth_token_secret']
);

$this->session->set_userdata($oauthData);
echo '<a href="https://www.tumblr.com/oauth/authorize?oauth_token=' . $data['oauth_token'].'"> Login With Tumblr </a>';
} else {
$verifier = $_GET['oauth_verifier'];
// use the stored tokens
$client->setToken($this->session->userdata('t'), $this->session->userdata('s'));
// to grab the access tokens
$resp = $requestHandler->request('POST', 'oauth/access_token', array('oauth_verifier' => $verifier));
$out = $result = $resp->body;
$data = array();
parse_str($out, $data);
// and print out our new keys we got back
$token = $data['oauth_token'];
$secret = $data['oauth_token_secret'];
//echo "token: " . $token . "<br/>secret: " . $secret;

// and prove we're in the money
$client = new Tumblr\API\Client($consumerKey, $consumerSecret, $token, $secret);
$info = $client->getUserInfo();
echo "<br/><br/>congrats " . $info->user->name . "!";
}
}
}

This example simply authenticate with Tumblr OAuth. You can use this for your application’s login system by checking user if new and storing necessary data into your database.

You may also like this posts:
i.) Authenticate with Facebook 

ii.) Authenticate with Gmail.Gmail.

Thank you for reading this post. we hope you like this Post, Please feel free to comment below, your suggestion. if you face any issue with this code let us know. We’d love to help!

Bunch Files Upload: Codeigniter Multi Files Upload Example

How upload bunch of files into server? In this tutorial we will see how to achieve this. Codeigniter upload library allows to upload files easily. Codeigniter’s Upload library comes with many configurations.Here is the full example of multiple file upload.

Creating Views:

Create a view file called upload.php views inside application/views directory.Here you need to define input file type and inside file type input, put multiple attribute which is new in HTML5. Multiple attribute of input file allows multiple file selection through file explorer window.Please find below the code of view.

upload.php

<!DOCTYPE html>
<html>
<head>
<title>Multiple File Upload in Codeigniter</title>
</head>
<body>
<center>
<h3><u>Multiple File Upload in Codeigniter</u></h3>
<h4><?php
if(!empty($this->session->flashdata('success'))){
echo $this->session->flashdata('success');
}
if(!empty($this->session->flashdata('error'))){
echo $this->session->flashdata('error');
}

?></h4>
<form method="post" enctype="multipart/form-data" action="<?php echo base_url('MultipleFileUploadController/upload'); ?>">
<fieldset>
<legend>Personal Info</legend>
Gallery Id: <input type="text" name="gallery_id"><br><br>
File : <input type="file" name="myfile[]" multiple="multiple"><br><br>
<input type="submit" name="upload"><br>
</fieldset>
</form>
</center>
</body>
</html>

Creating Controller and Multi Files Upload setup:

Next, Create a controller file named MultipleFileUploadController.php views inside application/controllers directory. Here we will load upload library and put all functions of multiple uploading.Here is how code looks.

class MultipleFileUploadController extends CI_Controller
{
function __construct()
{
parent::__construct();
$this->load->model('MultipleFileUploadModel');
}
public function index()
{
$this->load->view('upload');
}
public function upload(){

$count = count($_FILES['myfile']['name']);
for ($i=0; $i < $count; $i++) {
$_FILES['file']['name'] = $_FILES['myfile']['name'][$i];
$_FILES['file']['type'] = $_FILES['myfile']['type'][$i];
$_FILES['file']['tmp_name'] = $_FILES['myfile']['tmp_name'][$i];
$_FILES['file']['error'] = $_FILES['myfile']['error'][$i];
$_FILES['file']['size'] = $_FILES['myfile']['size'][$i];
$config['upload_path'] = 'uploads/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 100;
$config['max_width'] = 1024;
$config['max_height'] = 768;
$config['file_name'] = $_FILES['myfile']['name'][$i];
$this->load->library('upload', $config);
$this->upload->initialize($config);
$this->upload->do_upload('file');
if($this->upload->do_upload('file')){
$file_data = $this->upload->data();
$data[$i]['gallery_id'] = $this->input->post('gallery_id');
$data[$i]['file_name'] = $file_data['file_name'];
$data[$i]['created_date'] = date('Y-m-d h:i:s');
}else{
$this->session->set_flashdata('error',$this->upload->display_errors());
redirect('Upload/index');
}
}
$this->MultipleFileUploadModel->save($data);
$this->session->set_flashdata('success','data has successfully inserted !');
redirect('MultipleFileUploadController');
}
}
?>

Creating Model:

Now, Create a model file named MultipleFileUploadModel.php views inside application/models directory. Here in model we will insert all file details into database table which is coming through an array. To insert array data here we will use insert_array_batch query builder class of codeigniter.

<?php
class MultipleFileUploadModel extends CI_Model{
function __construct(){
parent:: __construct();
}
public function save($data){
$this->db->insert_batch('multiple_file_upload',$data);
}
}
?>

That’s all.Now you can test it finally.

Thank you for reading this post. we hope you like this Post, Please feel free to comment below, your suggestion and problems if you face – let us know. We’d love to help!

Facebook OAuth: Authenticate with Facebook in Codeigniter

How to Authenticate with Facebook ? In this post I would like to show how we can get authenticate with Facebook using codeigniter. Facebook OAuth API allow to authenticate user into web applications by using their Facebook account. Follow me I will show you step by step how we can achieve this.

Get Facebook OAuth Credentials:

Before integrating Facebook authentication into our application, we need to create some Facebook OAuth credentials.To create oauth credential, Simple go to Facebook Developer Console and create new app and all oauth credentials.

Dashboard Facebook Developer

Create New App:

Simply Go to My Apps and click on Create New App.

Facebook OAuth: Facebook Create App

App Settings:

After creating new app go to the basic setting of the app and enter all details that required.

Facebook App Basic Setting

Setting Up in Codeigniter:

After Getting app id and secret key from Facebook you need to install  and setup Facebook  SDK into codeigniter application.

Installing Facebook SDK via Composer:

To install Facebook SDK via composer you need to run command from codeigniter project root directory as i am showing Below.

composer require Facebook/graph-sdk

Controller Creation:

Next, create a controller named FacebookLoginController.php inside application/controller directory and write below code.

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class FacebookLoginController extends CI_Controller {
public function __construct()
{
parent::__construct();
}

Public function index()
{
$fb = new Facebook\Facebook([
'app_id'=>'APP_ID', /* Replace with your app id */
'app_secret'=>'SECRET_KEY', /* Replace with your secret key */
'default_graph_version'=>'v2.2',
]);

$helper = $fb->getRedirectLoginHelper();
$permissions = ['email']; /* Optional permissions */
$loginUrl = $helper->getLoginUrl('https://localhost/myapp/FacebookLoginController/fbcallback', $permissions);
echo '<a href="' . htmlspecialchars($loginUrl) . '">Log in with Facebook!</a>';
}

Public function fbcallback()
{
$fb = new Facebook\Facebook([
'app_id'=>'APP_ID', /* Replace with your app id */
'app_secret'=>'SECRET_KEY', /* Replace with your secret key */
'default_graph_version'=>'v2.2',
]);

$helper = $fb->getRedirectLoginHelper();

try {
$accessToken = $helper->getAccessToken();
} catch(Facebook\Exceptions\FacebookResponseException $e) {
/* When Graph returns an error */
echo 'Graph returned an error: ' . $e->getMessage();
exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
/* When validation fails or other local issues */
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}

if (! isset($accessToken)) {
if ($helper->getError()) {
header('HTTP/1.0 401 Unauthorized');
echo "Error: " . $helper->getError() . "\n";
echo "Error Code: " . $helper->getErrorCode() . "\n";
echo "Error Reason: " . $helper->getErrorReason() . "\n";
echo "Error Description: " . $helper->getErrorDescription() . "\n";
} else {
header('HTTP/1.0 400 Bad Request');
echo 'Bad request';
}
exit;
}

/* Logged in */
echo '<h3>Access Token</h3>';
var_dump($accessToken->getValue());

/* The OAuth 2.0 client handler helps us manage access tokens */
$oAuth2Client = $fb->getOAuth2Client();

/* Get the access token metadata from /debug_token */
$tokenMetadata = $oAuth2Client->debugToken($accessToken);

/* Validation (these will throw FacebookSDKException's when they fail) */
$tokenMetadata->validateAppId('1933290566759752'); // Replace {app-id} with your app id
/* If you know the user ID this access token belongs to, you can validate it here */
/*$tokenMetadata->validateUserId('123'); */
$tokenMetadata->validateExpiration();

if (! $accessToken->isLongLived()) {
/* Exchanges a short-lived access token for a long-lived one */
try {
$accessToken = $oAuth2Client->getLongLivedAccessToken($accessToken);
} catch (Facebook\Exceptions\FacebookSDKException $e) {
echo "<p>Error getting long-lived access token: " . $e->getMessage() . "</p>\n\n";
exit;
}
}
}
}
This example simply authenticate with Facebook OAuth. You can use this for your application’s login system by checking user if new and storing necessary data into your database.
Thank you for reading this post. we hope you like this Post, Please feel free to comment below, your suggestion. if you face any issue with this code let us know. We’d love to help!