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', 'OGRGb3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xTT0='),
(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;

10 comments:

  1. Very nice and advance tutorials JUST LOVE IT!!!

    ReplyDelete
  2. REAL SOURCE OF LEARNING WEB DEVELOPMENT

    ReplyDelete
  3. Thanx Sir how to get secrete key and $secret_iv

    ReplyDelete
  4. Hello! Once I've created files and such i went to my browser to run the web/script and got the following error message:

    "DataTables warning: table id=user_data - Invalid JSON response. For more information about this error, please see http://datatables.net/tn/1"

    I have no idea of what i could be...

    Thanks in advance.

    ReplyDelete
  5. For Anybody Reading this Article , it's a good explain of encrypt and decrypt but it's not do the job . any unencrypted post could be taken & use by MAN(middle man) sitting between client and server.
    After 1 week research on google with no success I did encryption in client side (Mixing JS&PHP).It's possible but not easy.

    ReplyDelete
  6. How to sort Encrypted Columns ?

    ReplyDelete
  7. Please Help!

    How to sort encrypted columns?

    ReplyDelete