Showing posts with label encryption. Show all posts
Showing posts with label encryption. Show all posts

Thursday, 4 October 2018

Data Encryption and Decryption In CodeIgniter

Data Encryption and Decryption In CodeIgniter - 1



Data Encryption and Decryption In CodeIgniter - 2



Data Encryption and Decryption In CodeIgniter - 3




Do you know what is data encryption and decryption in Web development, so we have explain you data encryption and decryption is to convert plain text into random alphanumeric with special character and that string has no any meaning. So when data store into Mysql database then it has been encrypted and when that data we want see on web page then that will be converted into plain string format in it's original meaning.

Most of web developers has used data encryption for store their highly secured data like password, credit card number OTP etc. Because this type of data is very important, so if someone has hack this data then he can misuse this type data. For this we have to store this type of data in encryption form, so if someone has hack our data then he cannot use this type of data because it has been store in encrytion form and it this can be decrypted by using encryption key which has been used for decrypt this data.

If you have used Codeigniter framework for your web development, then data encryption and decryption will be much easier than using simple PHP script. Because Codeigniter has it's own encryption library for encrypt and decrypt data. You has to just load library and use that library function then data will be easily encrypted and decrypted.

Now one question aris in your mind how can we load Codeigniter encryption library, for this you have to write following code, this code will load encryption library in your code environment.


<?php

$this->load->library('encrypt');

?>







Once this library has been load then by using this encrypt library object we can access different method of data encryption and decryption of this library by using this $this->encrypt. Before using this library in our working code for data encrypt and decrypt, first we have to set the encryption key in our Codeigniter framework. This key is used by different library and helper of Codeigniter like Session, Encrypt etc. By using this key it has cryptographic process and based on this key it has encrypt and decrypt data. That means data will be plain text to encrypted form by using key and from encryted form to plain text by using this encryption key. So, once you has define this key then after you do not change this key otherwise your encrypted data will be lost.

This is simple key in which we can use random character with alphanumeric and not plain string and it must be 32 characters long. For define this encryption key we have go to application/config/config.php file. In this file you have to file below code and define your encryption key.


<?php

$config['encryption_key'] = "YOUR KEY"; 

?>


After define your encryption key in your Codeigniter framwork, now we can use Encrypt library of Codeigniter for data encryption and decryption. For convert plain text to encrypted string we can use following method of encrypt library of Codeigniter.


<?php

$this->encrypt->encode()

?>


Once data has been encrypted and store in database, now again we want to convert into plain text form. For this we can use following method of Encrypt library of Codeigniter.


<?php

$this->encrypt->decode();

?>


Now you want to learn how can we use this encrypt library for data encryption and decryption in real example, so below we have make simple example of Codeigniter Crud, in which we have define step by step how data will be encrypted when it has been insert into Mysql data. That means we have define How can we insert encrypted data into Mysql database by using Codeigniter Encrypt Library.

Once encypted data has been store into Mysql database, now we want to display encrypted data on web page in plain text form. So by using Codeigniter Encrypt library we have define how can we fetch encrypted data from Mysql database and display on web page in plain text form in tabular format. Here we have also define how can we Codeigniter Encrypt library for edit or update encrypted data. Below you can find complete source code code for Insert Update and Fetch encyrption and decryption data in Codeigniter.

Database


Following script will help you to make table in your Mysql database.







--
-- Database: `testing`
--

-- --------------------------------------------------------

--
-- Table structure for table `sample_data`
--

CREATE TABLE `sample_data` (
  `id` int(10) NOT NULL,
  `first_name` text NOT NULL,
  `last_name` text NOT NULL,
  `age` text NOT NULL,
  `gender` text NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Indexes for dumped tables
--

--
-- Indexes for table `sample_data`
--
ALTER TABLE `sample_data`
  ADD PRIMARY KEY (`id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `sample_data`
--
ALTER TABLE `sample_data`
  MODIFY `id` int(10) NOT NULL AUTO_INCREMENT;


Controllers - EncryptionDecryption.php


This is controllers source code, in which you can find code for Insert data, Fetch data and Update data. How can we have load Encrypt Library and how we have use encode() and decode() method of Encrypt library for data encryption and decryption.


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

class EncryptionDecryption extends CI_Controller {

 function index()
 {
  $this->load->model('encryptiondecryption_model');
  $this->load->library('encrypt');
  $data['data'] = $this->encryptiondecryption_model->fetch_data();
  $this->load->view('encryption_decryption', $data);
 }
 
 function insert()
 {
  $this->load->view('insert_data');
 }

 function insert_validation()
 {
  $this->load->library('form_validation');
  $this->form_validation->set_rules('first_name', 'First Name', 'required|trim');
  $this->form_validation->set_rules('last_name', 'Last Name', 'required|trim');
  $this->form_validation->set_rules('age', 'Age', 'required|numeric|trim');
  $this->form_validation->set_rules('gender', 'Gender', 'required|trim');
  if($this->form_validation->run() == false)
  {
   $this->insert();
  }
  else
  {
   $this->load->library('encrypt');

   $data = array(
    'first_name' => $this->encrypt->encode($this->input->post('first_name')),
    'last_name'  => $this->encrypt->encode($this->input->post('last_name')),
    'age'   => $this->encrypt->encode($this->input->post('age')),
    'gender'  => $this->encrypt->encode($this->input->post('gender')),
   );
   $this->load->model('encryptiondecryption_model');
   $this->encryptiondecryption_model->insert($data);
   $this->session->set_flashdata('action', 'Data Inserted');
   redirect('encryptiondecryption');
  }
 }

 function edit()
 {
  $this->load->library('encrypt');
  $this->load->model('encryptiondecryption_model');
  $data['data'] = $this->encryptiondecryption_model->fetch_single_data($this->uri->segment(3));
  $this->load->view('edit_data', $data);
 }

 function edit_validation()
 {
  $this->load->library('form_validation');
  $this->form_validation->set_rules('first_name', 'First Name', 'required|trim');
  $this->form_validation->set_rules('last_name', 'Last Name', 'required|trim');
  $this->form_validation->set_rules('age', 'Age', 'required|numeric|trim');
  $this->form_validation->set_rules('gender', 'Gender', 'required|trim');
  if($this->form_validation->run() == false)
  {
   $this->edit();
  }
  else
  {
   $this->load->library('encrypt');

   $data = array(
    'first_name' => $this->encrypt->encode($this->input->post('first_name')),
    'last_name'  => $this->encrypt->encode($this->input->post('last_name')),
    'age'   => $this->encrypt->encode($this->input->post('age')),
    'gender'  => $this->encrypt->encode($this->input->post('gender')),
   );
   $this->load->model('encryptiondecryption_model');

   $this->encryptiondecryption_model->edit($this->input->post('hidden_id'), $data);

   $this->session->set_flashdata('action', 'Data Updated');
   redirect('encryptiondecryption');
  }
 }
 
}

?>


Models - EncryptionDecryption_model.php


This is Mysql database side operation code for Insert data into Mysql table, fetch single data and select all data from Mysql table and update or edit data option.


<?php
class EncryptionDecryption_model extends CI_Model
{
 function insert($data)
 {
  $this->db->insert('sample_data', $data);
 }

 function fetch_data()
 {
  $this->db->order_by('id', 'DESC');
  $query = $this->db->get('sample_data');
  return $query;
 }

 function fetch_single_data($id)
 {
  $this->db->where('id', $id);
  return $this->db->get('sample_data');
 }

 function edit($id, $data)
 {
  $this->db->where('id', $id);
  $this->db->update('sample_data', $data);
 }
}

?>


Views - insert_data.php


This is views file source code and below file will display insert data form on web page page and this page has been load by insert() method of Controller.


<html>
<head>
    <title>Codeigniter Encryption and Decryption - Insert Data</title>
    
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
 <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
    <style>
    body
    {
     background-color: #f1f1f1;
    }
    .box
    {
     width: 600px;
     margin:0 auto;
     background-color: #fff;
     border:1px solid #ccc;
     border-radius: 5px;
     padding:16px;
    }
 </style>
</head>
<body>
 <div class="container">
  <br />
  <br />
  <div class="box">
   <h3 align="center">Codeigniter3 Encryption and Decryption - Insert Data</h3>
   <br />
            <?php
            if(validation_errors() != '')
            {
                echo '
                <div class="alert alert-danger alert-dismissible">
                    <a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a>
                    ' . validation_errors() .'
                </div>
                ';
            }
            ?>
   <form method="post" action="<?php echo base_url(); ?>encryptiondecryption/insert_validation">
                <input type="text" name="first_name" class="form-control" placeholder="Enter First Name" />
                <br />
                <input type="text" name="last_name" class="form-control" placeholder="Enter Last Name" />
                <br />
                <input type="text" name="age" class="form-control" placeholder="Enter Age" />
                <br />
                <select name="gender" class="form-control">
                    <option value="male">Male</option>
                    <option value="female">Female</option>
                </select>
                <br />
                <div align="center">
                    <input type="submit" name="insert" class="btn btn-primary" value="Insert" />
                </div>
            </form>
  </div>
  <br />
 </div>
</body>
</html>


Views - encyption_decryption.php


This view file will display all mysql data in plain text form on web page in tabular format with edit button link and this file has been load by using index() method of Controller.


<html>
<head>
    <title>Codeigniter Encryption and Decryption - Fetch Data</title>
    
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
 <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
    <style>
    body
    {
     background-color: #f1f1f1;
    }
    .box
    {
     width: 800px;
     margin:0 auto;
     background-color: #fff;
     border:1px solid #ccc;
     border-radius: 5px;
     padding:16px;
    }
 </style>
</head>
<body>
 <div class="container">
  <br />
  <br />
  <div class="box">
   <h3 align="center">Codeigniter3 Encryption and Decryption - Fetch Data</h3>
   <br />
   <div class="table-responsive">
   <?php
   if($this->session->flashdata('action'))
   {
    echo '
    <div class="alert alert-success alert-dismissible">
      <a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a>
      '.$this->session->flashdata('action').'
     </div>
    ';
   }
   ?>
    <div align="right">
     <a href="<?php echo base_url(); ?>encryptiondecryption/insert" class="btn btn-primary btn-sm">Add</a>
    </div>
    <br />
    <table class="table table-striped table-bordered">
     <tr>
      <th>First Name</th>
      <th>Last Name</th>
      <th>Age</th>
      <th>Gender</th>
      <th>Edit</th>
     </tr>
     <?php
     foreach($data->result() as $row)
     {
      echo '
      <tr>
       <td>'.$this->encrypt->decode($row->first_name).'</td>
       <td>'.$this->encrypt->decode($row->last_name).'</td>
       <td>'.$this->encrypt->decode($row->age).'</td>
       <td>'.$this->encrypt->decode($row->gender).'</td>
       <td><a href="'.base_url().'encryptiondecryption/edit/'.$row->id.'">Edit</a></td>
      </tr>
      ';
     }
     ?>
    </table>
   </div>
  </div>
  <br />
 </div>
</body>
</html>


Views - edit_data.php


This views files has been used for edit or update data, it will load form with filled data for update and this file has been load by using edit() method of controller.


<html>
<head>
    <title>Codeigniter Encryption and Decryption - Update Data</title>
    
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
 <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
    <style>
    body
    {
     background-color: #f1f1f1;
    }
    .box
    {
     width: 600px;
     margin:0 auto;
     background-color: #fff;
     border:1px solid #ccc;
     border-radius: 5px;
     padding:16px;
    }
 </style>
</head>
<body>
 <div class="container">
  <br />
  <br />
  <div class="box">
   <h3 align="center">Codeigniter3 Encryption and Decryption - Update Data</h3>
   <br />
   <?php

            foreach($data->result() as $row)
            {
            ?>
            <script>
            $(document).ready(function(){
                $('#gender').val("<?php echo $this->encrypt->decode($row->gender); ?>");
            });
            </script>
            <form method="post" action="<?php echo base_url(); ?>encryptiondecryption/edit_validation">
                <input type="text" name="first_name" class="form-control" placeholder="Enter First Name" value="<?php echo $this->encrypt->decode($row->first_name); ?>" />
                <br />
                <input type="text" name="last_name" class="form-control" placeholder="Enter Last Name" value="<?php echo $this->encrypt->decode($row->last_name);?>" />
                <br />
                <input type="text" name="age" class="form-control" placeholder="Enter Age" value="<?php echo $this->encrypt->decode($row->age); ?>" />
                <br />
                <select name="gender" id="gender" class="form-control">
                    <option value="male">Male</option>
                    <option value="female">Female</option>
                </select>
                <br />
                <div align="center">
                    <input type="hidden" name="hidden_id" value="<?php echo $row->id; ?>" />
                    <input type="submit" name="insert" class="btn btn-primary" value="Edit" />
                </div>
            </form>
            <?php
            }

            ?>
  </div>
  <br />
 </div>
</body>
</html>


If you want to download complete file of this Insert Update and Fetch encrypted and decrypted data in Codeigniter tutorial, then you can download complete source code file by click on below download link.




Monday, 11 December 2017

Encryption and Decryption Form Data in PHP

This post will provide you how to make a two-way system for encrypt form data and decrypt that an encrypted string in PHP using Ajax JQuery. We have already seen many post in which we have store form data in Mysql table in simple original string format. But here we have discuss some security for store Form data using PHP. Here we will not insert form data in it's orignal form. But we will encryt form data using PHP code and then after we will store into Mysql table. So when user save form data then after we will encrypt form data and then after we will insert into Mysql table by using PHP script with Ajax Jquery.

Here we will discuss two way encryption and decryption of Encrypted string. That means once we will store form data in encrypted form and then after we want to display that encrypted string on their original format. So at that time we will decrypt that encrypted string by using PHP script and display on web page. So, it is called two way encrypt and decrpt string using PHP script. For encryption and decryption string in PHP we have use different PHP encrypt method like AES-256-CBC. We have use this PHP encrypt method for encrypt string. We have also use PHP hash() function for make encrypted string. We have also use different PHP function like openssl_encrypt() function for convert string to encrypted form and after this we have use base64_encode(). By using this both function we can encrypt string. For decrypt string we have use base64_decode() function and openssl_decrypt() function for decrypt encryted string. This way we can make two way encryption and decryption in PHP.

For Two way encryption and decryption in PHP depends on encryption key and initialization vector. If we have lost this two key then we cannot decrypt encrypted string. So string encryption is depends on this two keys and it it is lost then we cannot convert encrypted string. For discuss this things we have use simple Insert Update Delete and Select data example by using PHP script with Ajax Jquery. In this example first we will fetch encrypted data from Mysql table and convert into normal string and display on web page in Jquery Datatables. After this we will Insert form data into Mysql table. So for this we will encrypt form data and insert into Mysql table. Then after we want to update, so update first we want to fetch single user encrypted data and decrypt and display in form field. For this all crud operation we have use PHP Script with Ajax Jquery.






Source Code


database_connection.php



<?php
//database_connection.php
$connect = new PDO('mysql:host=localhost;dbname=testing', 'root', '');

?>


index.php



<?php
//index.php



?>
<!DOCTYPE html>
<html>
 <head>
  <title>How to Encrypt & Decrypt Form Data using PHP</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
  <script src="https://cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script>
  <script src="https://cdn.datatables.net/1.10.12/js/dataTables.bootstrap.min.js"></script>  
  <link rel="stylesheet" href="https://cdn.datatables.net/1.10.12/css/dataTables.bootstrap.min.css" />
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
 </head>
 <body>
  <br />
  <h2 align="center">How to Encrypt & Decrypt Form Data using PHP</h2>
  <br />
  <div class="container">
  
  <div class="row">
   <div class="col-lg-12">
    <div class="panel panel-default">
     <div class="panel-heading">
      <div class="col-lg-10 col-md-10 col-sm-8 col-xs-6">
       <div class="row">
        <h3 class="panel-title">User List</h3>
       </div>
      </div>
      <div class="col-lg-2 col-md-2 col-sm-4 col-xs-6">
       <div class="row" align="right">
        <button type="button" name="add" id="add_button" class="btn btn-success btn-xs">Add</button>     
       </div>
      </div>
      <div style="clear:both"></div>
     </div>
     <div class="panel-body">
      <div class="row">
       <div class="col-sm-12 table-responsive">
        <span id="alert_action"></span>
        <table id="user_data" class="table table-bordered table-striped">
         <thead><tr>
          <th>First Name</th>
          <th>Last Name</th>
          <th>Phone</th>
          <th>Email</th>
          <th>Edit</th>
          <th>Delete</th>
         </tr></thead>
        </table>
       </div>
      </div>
     </div>
    </div>
   </div>
  </div></div>
  <div id="userModal" class="modal fade">
   <div class="modal-dialog">
    <form method="post" id="user_form">
     <div class="modal-content">
      <div class="modal-header">
       <button type="button" class="close" data-dismiss="modal">&times;</button>
       <h4 class="modal-title">Add User</h4>
      </div>
      <div class="modal-body">
       <span id="validation_error"></span>
       <div class="form-group">
        <label>Enter First Name</label>
        <input type="text" name="first_name" id="first_name" class="form-control" />
       </div>
       <div class="form-group">
        <label>Enter Last Name</label>
        <input type="text" name="last_name" id="last_name" class="form-control" />
       </div>
       <div class="form-group">
        <label>Enter Phone No.</label>
        <input type="text" name="phone" id="phone" class="form-control" />
       </div>
       <div class="form-group">
        <label>Enter Email</label>
        <input type="email" name="email_address" id="email_address" class="form-control" />
       </div>
      </div>
      <div class="modal-footer">
       <input type="hidden" name="id" id="id"/>
       <input type="hidden" name="crud_action" id="crud_action"/>
       <input type="submit" name="action" id="action" class="btn btn-info" value="Add" />
       <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
      </div>
     </div>
    </form>
   </div>
  </div>
 </body>
</html>

<script>
$(document).ready(function(){
  
 $('#add_button').click(function(){
  $('#userModal').modal('show');
  $('#user_form')[0].reset();
  $('.modal-title').html("<i class='fa fa-plus'></i> Add User");
  $('#action').val('Add');
  $('#crud_action').val('Add');
 });
 
 var crud_action = 'fetch_all';
 
 var userdataTable = $('#user_data').DataTable({
  "processing":true,
  "serverSide":true,
  "order":[],
  "ajax":{
   url:"user_action.php",
   type:"POST",
   data:{crud_action:crud_action}
  },
  "columnDefs":[
   {
    "targets":[4, 5],
    "orderable":false,
   },
  ],
  "pageLength": 10
 });
 
 $(document).on('submit', '#user_form', function(event){
  
  event.preventDefault();
  
  var form_data = $(this).serialize();
  
  $.ajax({
   url:"user_action.php",
   method:"POST",
   data:form_data,
   dataType:"json",
   success:function(data)
   {
    if(data.error != '')
    {
     $('#validation_error').html(data.error);
    }
    else
    {
     $('#alert_action').html(data.message);
     $('#user_form')[0].reset();
     $('#userModal').modal('hide');
     userdataTable.ajax.reload();
    }
     
   }
  });  
 });
 
 $(document).on('click', '.update', function(){
  var id = $(this).attr("id");
  crud_action = "fetch_single";
  $.ajax({
   url:"user_action.php",
   method:"POST",
   data:{id:id, crud_action:crud_action},
   dataType:"JSON",
   success:function(data)
   {
    $('#validation_error').html('');
    $('#userModal').modal('show');
    $('.modal-title').text('Edit User');
    $('#first_name').val(data.first_name);
    $('#last_name').val(data.last_name);
    $('#phone').val(data.phone);
    $('#email_address').val(data.email_address);
    $('#id').val(id);
    $('#crud_action').val('Edit');
    $('#action').val('Edit');
   }
  });
 });
 
 $(document).on('click', '.delete', function(){
  var id = $(this).attr("id");
  crud_action = "Delete";
  if(confirm("Are you sure you want to delete this?"))
  {
   $.ajax({
    url:"user_action.php",
    method:"POST",
    data:{id:id, crud_action:crud_action},
    dataType:"json",
    success:function(data)
    {
     $('#alert_action').html(data.message);
     $('#userModal').modal('hide');
     userdataTable.ajax.reload();
    }
   });
  }
  else
  {
   return false;
  }
 });
 
});
</script>


user_action.php



<?php 

//user_action.php

include('database_connection.php');

include('function.php');

if(isset($_POST["crud_action"]))
{
 if($_POST["crud_action"] == 'fetch_all')
 {
  $query = '';
  
  $output = array();

  $order_column = array('first_name', 'last_name', 'phone', 'email');

  $query .= "
   SELECT * FROM tbl_user 
  ";

  if(isset($_POST["search"]["value"]))
  {
   $query .= 'WHERE first_name LIKE "%'.convert_string('encrypt', $_POST["search"]["value"]).'%" ';
   $query .= 'OR last_name LIKE "%'.convert_string('encrypt', $_POST["search"]["value"]).'%" ';
   $query .= 'OR phone LIKE "%'.convert_string('encrypt', $_POST["search"]["value"]).'%" ';
   $query .= 'OR email LIKE "%'.convert_string('encrypt', $_POST["search"]["value"]).'%" ';
  }

  if(isset($_POST["order"]))
  {
   $query .= 'ORDER BY '.$order_column[$_POST['order']['0']['column']].' '.$_POST['order']['0']['dir'].' ';
  }
  else
  {
   $query .= 'ORDER BY id DESC ';
  }

  if($_POST["length"] != -1)
  {
   $query .= 'LIMIT ' . $_POST['start'] . ', ' . $_POST['length'];
  }

  $statement = $connect->prepare($query);

  $statement->execute();

  $result = $statement->fetchAll();

  $filtered_rows = $statement->rowCount();

  foreach($result as $row)
  {
   $sub_array = array();
   $sub_array[] = convert_string('decrypt', $row['first_name']);
   $sub_array[] = convert_string('decrypt', $row['last_name']);
   $sub_array[] = convert_string('decrypt', $row['phone']);
   $sub_array[] = convert_string('decrypt', $row['email']);
   $sub_array[] = '<button type="button" name="update" id="'.convert_string('encrypt', $row["id"]).'" class="btn btn-warning btn-xs update">Update</button>';
   $sub_array[] = '<button type="button" name="delete" id="'.convert_string('encrypt', $row["id"]).'" class="btn btn-danger btn-xs delete">Delete</button>';
   $output[] = $sub_array;
  }

  $data = array(
   "draw"    => intval($_POST["draw"]),
   "recordsTotal"  => $filtered_rows,
   "recordsFiltered" => get_total_all_records($connect),
   "data"    => $output
  );
 }
 elseif($_POST["crud_action"] == 'fetch_single')
 {
  $id = convert_string('decrypt', $_POST["id"]);
  $query = "
  SELECT * FROM tbl_user 
  WHERE id = '$id'
  ";
  $statement = $connect->prepare($query);
  $statement->execute();
  $result = $statement->fetchAll();
  foreach($result as $row)
  {
   $data['first_name'] = convert_string('decrypt', $row['first_name']);
   $data['last_name'] = convert_string('decrypt', $row['last_name']);
   $data['phone'] = convert_string('decrypt', $row['phone']);
   $data['email_address'] = convert_string('decrypt', $row['email']);
  }
 }
 elseif($_POST["crud_action"] == 'Delete')
 {
  $id = convert_string('decrypt', $_POST["id"]);
  $query = "
  DELETE FROM tbl_user 
  WHERE id = '$id'
  ";
  $statement = $connect->prepare($query);
  $statement->execute();
  $data = array(
   'message'  => '<div class="alert alert-success">User Deleted</div>'
  );
 }
 else
 {
  $message = '';
  $error = '';
  $first_name = '';
  $last_name = '';
  $phone = '';
  $email_address = '';
  if(empty($_POST["first_name"]))
  {
   $error .= '<p class="text-danger">First Name is Required</p>';
  }
  else
  {
   if (!preg_match("/^[a-zA-Z]*$/",$_POST["first_name"]))
   {
    $error .= '<p class="text-danger">Only Alphabet allowed in First Name</p>';
   }
   else
   {
    $first_name = clean_text($_POST["first_name"]);
   }
  }
  
  if(empty($_POST["last_name"]))
  {
   $error .= '<p class="text-danger">Last Name is Required</p>';
  }
  else
  {
   if (!preg_match("/^[a-zA-Z]*$/",$_POST["last_name"]))
   {
    $error .= '<p class="text-danger">Only Alphabet allowed in Last Name</p>';
   }
   else
   {
    $last_name = clean_text($_POST["last_name"]);
   }
  }
  
  if(empty($_POST["phone"]))
  {
   $error .= '<p class="text-danger">Phone Number is Required</p>';
  }
  else
  {
   if (!preg_match("/^[0-9]*$/",$_POST["phone"]))
   {
    $error .= '<p class="text-danger">Only Numbers allowed in Phone</p>';
   }
   else
   {
    $phone = clean_text($_POST["phone"]);
   }
  }
  
  if(empty($_POST["email_address"]))
  {
   $error .= '<p class="text-danger">Email Address is Required</p>';
  }
  else
  {
   if (!filter_var($_POST["email_address"], FILTER_VALIDATE_EMAIL))
   {
    $error .= '<p class="text-danger">Invalid email format</p>'; 
   }
   else
   {
    $email_address = clean_text($_POST["email_address"]);
   }
  }
  
  if($error == '')
  {
   $first_name = convert_string('encrypt', $first_name);
   $last_name = convert_string('encrypt', $last_name);
   $phone = convert_string('encrypt', $phone);
   $email_address = convert_string('encrypt', $email_address);
   if($_POST["crud_action"] == "Add")
   {
    $query = "
    SELECT * FROM tbl_user 
    WHERE email = '$email_address'
    ";
    $statement = $connect->prepare($query);
    $statement->execute();
    $no_of_row = $statement->rowCount();
    if($no_of_row > 0)
    {
     $error = '<div class="alert alert-danger">Email Already Exists</div>';
    }
    else
    {
     $query = "
     INSERT INTO tbl_user (first_name, last_name, phone, email) 
     VALUES('".$first_name."', '".$last_name."', '".$phone."', '".$email_address."')
     ";
     $message = '<div class="alert alert-success">User Added</div>';
    }
   }
   if($_POST["crud_action"] == "Edit")
   {
    $id = convert_string('decrypt', $_POST["id"]);
    $query = "
    UPDATE tbl_user 
    SET first_name = '$first_name', 
    last_name = '$last_name', 
    phone = '$phone', 
    email = '$email_address' 
    WHERE id = '$id'
    ";
    $message = '<div class="alert alert-success">User Edited</div>';
   }
   $statement = $connect->prepare($query);
   $statement->execute();
   $result = $statement->fetchAll();
   if(isset($result))
   {
    $data = array(
     'error'   => $error,
     'message'  => $message
    );
   }
  }
  else
  {
   $data = array(
    'error'   => $error,
    'message'  => $message
   );
   
  }
 }
 echo json_encode($data);
}

?>


function.php



<?php

//function.php

function get_total_all_records($connect)
{
 $statement = $connect->prepare('SELECT * FROM tbl_user');
 $statement->execute();
 return $statement->rowCount();
}

function clean_text($string)
{
 $string = trim($string);
 $string = stripslashes($string);
 $string = htmlspecialchars($string);
 return $string;
}

function convert_string($action, $string)
{
 $output = '';
 $encrypt_method = "AES-256-CBC";
    $secret_key = 'eaiYYkYTysia2lnHiw0N0vx7t7a3kEJVLfbTKoQIx5o=';
    $secret_iv = 'eaiYYkYTysia2lnHiw0N0';
    // hash
    $key = hash('sha256', $secret_key);
 $initialization_vector = substr(hash('sha256', $secret_iv), 0, 16);
 if($string != '')
 {
  if($action == 'encrypt')
  {
   $output = openssl_encrypt($string, $encrypt_method, $key, 0, $initialization_vector);
   $output = base64_encode($output);
  } 
  if($action == 'decrypt') 
  {
   $output = openssl_decrypt(base64_decode($string), $encrypt_method, $key, 0, $initialization_vector);
  }
 }
 return $output;
}

?>


Database



--
-- Database: `testing`
--

-- --------------------------------------------------------

--
-- Table structure for table `tbl_user`
--

CREATE TABLE IF NOT EXISTS `tbl_user` (
  `id` int(11) NOT NULL,
  `first_name` varchar(250) NOT NULL,
  `last_name` varchar(250) NOT NULL,
  `phone` varchar(30) NOT NULL,
  `email` varchar(200) NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=14 DEFAULT CHARSET=latin1;

--
-- Dumping data for table `tbl_user`
--

INSERT INTO `tbl_user` (`id`, `first_name`, `last_name`, `phone`, `email`) VALUES
(1, 'QlRsWTJ2azNjb2NLb2N4NjcyRkxFQT09', 'TlViVDljWHFDNTY5eHU3UTBQQmsvQT09', 'eHp4aVR4STZ4SGNrTm9hQ0dDU0lJZz', 'cTM0N2RCUVBHTTNZRGhKZFdXM2VqNlNnVVUxYTd2b3hIaThuY3JKNEFQVT0='),
(2, 'VVdQTUhpTG80a1VOMW1DL1JsL01oZz09', 'WnRkUEJjNGRGUlFXRWVpMWJWUkRlQT09', 'Q1NMNUUvdE1RRUlqVWtJZWs4aEIwQT', 'NGNrMkVnUDNEb1psQ2NwSEVKMTY1b1FzcGUrRjVDMDhCU2g2WGdvK0Vzdz0='),
(3, 'ZFlCUEtPNFllUGNBMTZCMWxiVnE2dz09', 'VFJLNjU5MUFKengrVTAwY0g5MGtZZz09', 'NEcvUnRRbVVoSHVJQXozL0E3NGRVQT', 'OGRGb3F0bjRERE1rbllEa3JNL1JkVWRZdHdXZ0wwenlqL3kyYWZWSGw5cz0='),
(4, 'Q2ovYWcvaE5SUmN5L2hKQkZWaFNQUT09', 'enROUUNFOStYRmJyVHRYWWVYeUd3QT09', 'd3RodWxEVzFHRWkzTzYxSk1tSzFxZz', 'K3IrNWVHZ2ovRlMvSzh1akMzVmgvU096c2Rxc3hOZndjMWh4aVAyazI2ST0='),
(5, 'UmtyUVFERmNacGxuV2VxejdIM2o2dz09', 'Q0ZzSHU5K0ZQOVc2NWpSNDA5WWljUT09', 'ZVpRcTJyRVNabXZzekZUeXovYm52dz', 'U2ZURXlvVXcwNngwMTZEY21zdHY5empWcmU3MHdsSHN2SDE5eWJ1OFplbz0='),
(6, 'bG5SNFVybk5JcVM3MmV0ZXQ0L0YrUT09', 'd0E4Z1hqVTZqMlhvY2N5MHR4LzhqZz09', 'TXozaEhtVk5tZjBNY0NxR1ljS04zQT', 'WHpZeW1zQVNSSG1UYldlVkJia1QvUk5PbmlJamxlOUtqbytXRWkwWkNwND0='),
(7, 'UVh4a0QyWCtjN1F5YWdTVnpxdk1YUT09', 'OElTMlVVQjBscG01YmNFTGkzeWMxdz09', 'd2tQeU14NnJZeU1WeHFBSkI5TUswZz', 'NFNmNjNWaDFnR0d6N3dnOXVwTnMwM0VSTWZlYjQvc0FqUzBJbVBheXA3Yz0='),
(8, 'NFd1ZjJrVm8zQWVqN3paa3I2MHJKQT09', 'UVkzb2wwdkVzbFRpS3FjdVNIMEk1QT09', 'ZThROGpQa0NJTHlKU2c3U3VtTWxOZz', 'cW5ia3hETmJwVGhKd1hRTmlYT1A4cVEwd1VMc3VnZTltVjVXaEF2RmcxST0='),
(9, 'alpYNHpWZlZldFRSckdHMnpCS2dJZz09', 'UFdCZFhyMEFSY0t0VWlkdWxQMFA3QT09', 'N1N1YmphQkVuUi9ReEdoS3hQS2psQT', 'bE5GbkxrcVJiTWZ2SGhYaDAzc2FPVHAzcE5qUVQ4R1QrWWtyTUJJVHIxTT0='),
(10, 'U1U0U0FEREJXOXo5VEk1VGdoVE9tZz09', 'NC9IWnE0R1k4VHhFVkdMdjVtZ0x6QT09', 'VDRBT3puTEVUREtnMTQ3K3ZUcTlmQT', 'N1RPV2xObi92dTBGMXVhOWFlUEgzTGxENkhUeUVhQzRDUFQzNVhHdzQxND0='),
(11, 'dzUwT2xnSFRsdVdaaWNhMHZScXFhUT09', 'dUkrMmkveWFaWTJtcUNpM0pDZ1ZXQT09', 'dFZsY0RGQVV1cThaSGRvZ1JYUDEydz', 'c25pYkJiNStiaEZFNkZpazE0VTFMZmxKSHJsY3lVWmtQUWwrMnByQzhEST0='),
(12, 'RC9WK0IxSWorOEh4alpobG10ODgyQT09', 'VGdiSHZSbkh5enQzOEJxbFlvUDRXZz09', 'L3c0cTZQM1lKcXNrQ0lQZ3dDd2hMUT', 'VGthd3hZVXVqMmM4MXRPYWxEVUVlLzZFajZ5b2lNOStTNytSZUJxL2QwND0='),
(13, 'QllBN0g2SlNLd3FqRHFUUDRZR0VnZz09', 'M0VMWG5RT21PYkRLRUdvVTBpRnA0QT09', 'ZW5yb0wwTytwNEVORXQvZjFRdVpxUT', 'cExuK1V2ZXVHRzNTZGNMUmZrY215aHN5R3didWovMWtVcVBlUFZCUzM5bz0=');

--
-- Indexes for dumped tables
--

--
-- Indexes for table `tbl_user`
--
ALTER TABLE `tbl_user`
  ADD PRIMARY KEY (`id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `tbl_user`
--
ALTER TABLE `tbl_user`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=14;