Tagged: how to encrypt post data in php

PHP Encryption and Decryption Form POST Data 0

PHP Encryption and Decryption Form POST Data

PHP Encryption and Decryption Form POST Data

In this Post We Will Explain About is PHP Encryption and Decryption Form POST Data With Example and Demo.Welcome on Pakainfo.com – Examples, The best For Learn web development Tutorials,Demo with Example! Hi Dear Friends here u can know to Encrypt Post Data PHP Solution without SSL Example

In this post we will show you Best way to implement Encrypt and decrypt forms with AES and RSA in PHP, hear for How to Encrypt & Decrypt Form Data using PHP Ajax with Download .we will give you demo,Source Code and examples for implement Step By Step Good Luck!.

Database

CREATE TABLE IF NOT EXISTS `tbl_student` (
  `id` int(11) NOT NULL,
  `stud_fname` varchar(250) NOT NULL,
  `stud_lname` varchar(250) NOT NULL,
  `mobile` varchar(30) NOT NULL,
  `email` varchar(200) NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=14 DEFAULT CHARSET=latin1;

ALTER TABLE `tbl_student`
  ADD PRIMARY KEY (`id`);
  
  
ALTER TABLE `tbl_student`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=14;
  

db_config.php

<?php
//db_config.php
$connect = new PDO('mysql:host=localhost;dbname=Your_database_name', 'Host_name', 'Your_password');
?>

index.php

<!DOCTYPE html>
<html>
 <head>
  <title>PHP Form Encryption: Encrypt and decrypt forms with AES and RSA</title>
 </head>
 <body>
  <br />
  <h2 align="center">Encryption and Decryption Form Data in PHP</h2>
  <br />
  <div class="container">
  
  <div class="row">
   <div class="col-md-12">
    <div class="panel panel-primary">
     <div class="panel-heading">
      <div class="col-md-10 col-md-10 col-sm-8 col-md-6">
       <div class="row">
        <h3 class="panel-title">Student List</h3>
       </div>
      </div>
      <div class="col-md-2 col-md-2 col-sm-4 col-md-6">
       <div class="row" align="right">
        <button type="button" name="add" id="insert_btn" class="btn btn-success btn-md">Student 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="action_alrt"></span>
        <table id="student_data" class="table">
         <thead><tr>
          <th>Student First Name</th>
          <th>Student Last Name</th>
          <th>Student Mobile</th>
          <th>Student Email</th>
          <th>Student Edit</th>
          <th>Student Delete</th>
         </tr></thead>
        </table>
       </div>
      </div>
     </div>
    </div>
   </div>
  </div></div>
  <div id="liveStudentMdl" class="modal fade">
   <div class="modal-dialog">
    <form method="post" id="studentForm">
     <div class="modal-content">
      <div class="modal-header">
       <button type="button" class="close" data-dismiss="modal">×</button>
       <h4 class="modal-title">Add Student</h4>
      </div>
      <div class="modal-body">
       <span id="error_validation"></span>
       <div class="form-group">
        <label>Enter First Name</label>
        <input type="text" name="stud_fname" id="stud_fname" class="form-control" />
       </div>
       <div class="form-group">
        <label>Enter Last Name</label>
        <input type="text" name="stud_lname" id="stud_lname" class="form-control" />
       </div>
       <div class="form-group">
        <label>Enter Phone No.</label>
        <input type="text" name="mobile" id="mobile" class="form-control" />
       </div>
       <div class="form-group">
        <label>Enter Email</label>
        <input type="email" name="stud_emailaddr" id="stud_emailaddr" class="form-control" />
       </div>
      </div>
      <div class="modal-footer">
       <input type="hidden" name="id" id="id"/>
       <input type="hidden" name="model_crud_opt" id="model_crud_opt"/>
       <input type="submit" name="action" id="action" class="btn btn-info" value="Add" />
       <button type="button" class="btn btn-primary" data-dismiss="modal">Close</button>
      </div>
     </div>
    </form>
   </div>
  </div>
 </body>
</html>

Include External Libs

  <script src="2.2.0/jquery.min.js"></script>
  <link rel="stylesheet" href="css/bootstrap.min.css" />
  <script src="jquery.dataTables.min.js"></script>
  <script src="js/dataTables.bootstrap.min.js"></script>  
  <link rel="stylesheet" href="css/dataTables.bootstrap.min.css" />
  <script src="3.3.6/js/bootstrap.min.js"></script>

index.js

$(document).ready(function(){
  
 $('#insert_btn').click(function(){
  $('#liveStudentMdl').modal('show');
  $('#studentForm')[0].reset();
  $('.modal-title').html("<i class='fa fa-plus'></i> Add Student");
  $('#action').val('Add');
  $('#model_crud_opt').val('Add');
 });
 
 var model_crud_opt = 'fetch_all';
 
 var srydentdataTable = $('#student_data').DataTable({
  "processing":true,
  "serverSide":true,
  "order":[],
  "ajax":{
   url:"student_action.php",
   type:"POST",
   data:{model_crud_opt:model_crud_opt}
  },
  "columnDefs":[
   {
    "targets":[4, 5],
    "orderable":false,
   },
  ],
  "pageLength": 10
 });
 
 $(document).on('submit', '#studentForm', function(event){
  
  event.preventDefault();
  
  var form_data = $(this).serialize();
  
  $.ajax({
   url:"student_action.php",
   method:"POST",
   data:form_data,
   dataType:"json",
   success:function(data)
   {
    if(data.error != '')
    {
     $('#error_validation').html(data.error);
    }
    else
    {
     $('#action_alrt').html(data.message);
     $('#studentForm')[0].reset();
     $('#liveStudentMdl').modal('hide');
     srydentdataTable.ajax.reload();
    }
     
   }
  });  
 });
 
 $(document).on('click', '.update', function(){
  var id = $(this).attr("id");
  model_crud_opt = "fetch_single";
  $.ajax({
   url:"student_action.php",
   method:"POST",
   data:{id:id, model_crud_opt:model_crud_opt},
   dataType:"JSON",
   success:function(data)
   {
    $('#error_validation').html('');
    $('#liveStudentMdl').modal('show');
    $('.modal-title').text('Edit Student');
    $('#stud_fname').val(data.stud_fname);
    $('#stud_lname').val(data.stud_lname);
    $('#mobile').val(data.mobile);
    $('#stud_emailaddr').val(data.stud_emailaddr);
    $('#id').val(id);
    $('#model_crud_opt').val('Edit');
    $('#action').val('Edit');
   }
  });
 });
 
 $(document).on('click', '.delete', function(){
  var id = $(this).attr("id");
  model_crud_opt = "Delete";
  if(confirm("Are you sure you want to student delete this?"))
  {
   $.ajax({
    url:"student_action.php",
    method:"POST",
    data:{id:id, model_crud_opt:model_crud_opt},
    dataType:"json",
    success:function(data)
    {
     $('#action_alrt').html(data.message);
     $('#liveStudentMdl').modal('hide');
     srydentdataTable.ajax.reload();
    }
   });
  }
  else
  {
   return false;
  }
 });
 
});

student_action.php

<?php 

//student_action.php

include('db_config.php');

include('function.php');

if(isset($_POST["model_crud_opt"]))
{
 if($_POST["model_crud_opt"] == 'fetch_all')
 {
  $my_query = '';
  
  $results = array();

  $order_column = array('stud_fname', 'stud_lname', 'mobile', 'email');

  $my_query .= "
   SELECT * FROM tbl_student 
  ";

  if(isset($_POST["search"]["value"]))
  {
   $my_query .= 'WHERE stud_fname LIKE "%'.string_convert_data('encrypt', $_POST["search"]["value"]).'%" ';
   $my_query .= 'OR stud_lname LIKE "%'.string_convert_data('encrypt', $_POST["search"]["value"]).'%" ';
   $my_query .= 'OR mobile LIKE "%'.string_convert_data('encrypt', $_POST["search"]["value"]).'%" ';
   $my_query .= 'OR email LIKE "%'.string_convert_data('encrypt', $_POST["search"]["value"]).'%" ';
  }

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

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

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

  $statement->execute();

  $result = $statement->fetchAll();

  $filtered_rows = $statement->rowCount();

  foreach($result as $row)
  {
   $child_arr = array();
   $child_arr[] = string_convert_data('decrypt', $row['stud_fname']);
   $child_arr[] = string_convert_data('decrypt', $row['stud_lname']);
   $child_arr[] = string_convert_data('decrypt', $row['mobile']);
   $child_arr[] = string_convert_data('decrypt', $row['email']);
   $child_arr[] = '<button type="button" name="update" id="'.string_convert_data('encrypt', $row["id"]).'" class="btn btn-warning btn-md update">Update</button>';
   $child_arr[] = '<button type="button" name="delete" id="'.string_convert_data('encrypt', $row["id"]).'" class="btn btn-danger btn-md delete">Delete</button>';
   $results[] = $child_arr;
  }

  $data = array(
   "draw"    => intval($_POST["draw"]),
   "recordsTotal"  => $filtered_rows,
   "recordsFiltered" => get_total_all_records($connect),
   "data"    => $results
  );
 }
 elseif($_POST["model_crud_opt"] == 'fetch_single')
 {
  $id = string_convert_data('decrypt', $_POST["id"]);
  $my_query = "
  SELECT * FROM tbl_student 
  WHERE id = '$id'
  ";
  $statement = $connect->prepare($my_query);
  $statement->execute();
  $result = $statement->fetchAll();
  foreach($result as $row)
  {
   $data['stud_fname'] = string_convert_data('decrypt', $row['stud_fname']);
   $data['stud_lname'] = string_convert_data('decrypt', $row['stud_lname']);
   $data['mobile'] = string_convert_data('decrypt', $row['mobile']);
   $data['stud_emailaddr'] = string_convert_data('decrypt', $row['email']);
  }
 }
 elseif($_POST["model_crud_opt"] == 'Delete')
 {
  $id = string_convert_data('decrypt', $_POST["id"]);
  $my_query = "
  DELETE FROM tbl_student 
  WHERE id = '$id'
  ";
  $statement = $connect->prepare($my_query);
  $statement->execute();
  $data = array(
   'message'  => '<div class="alert alert-success">Student Deleted</div>'
  );
 }
 else
 {
  $message = '';
  $error = '';
  $stud_fname = '';
  $stud_lname = '';
  $mobile = '';
  $stud_emailaddr = '';
  if(empty($_POST["stud_fname"]))
  {
   $error .= '<p class="text-danger">First Name is Required</p>';
  }
  else
  {
   if (!preg_match("/^[a-zA-Z]*$/",$_POST["stud_fname"]))
   {
    $error .= '<p class="text-danger">Only Alphabet allowed in First Name</p>';
   }
   else
   {
    $stud_fname = clean_text($_POST["stud_fname"]);
   }
  }
  
  if(empty($_POST["stud_lname"]))
  {
   $error .= '<p class="text-danger">Last Name is Required</p>';
  }
  else
  {
   if (!preg_match("/^[a-zA-Z]*$/",$_POST["stud_lname"]))
   {
    $error .= '<p class="text-danger">Only Alphabet allowed in Last Name</p>';
   }
   else
   {
    $stud_lname = clean_text($_POST["stud_lname"]);
   }
  }
  
  if(empty($_POST["mobile"]))
  {
   $error .= '<p class="text-danger">Phone Number is Required</p>';
  }
  else
  {
   if (!preg_match("/^[0-9]*$/",$_POST["mobile"]))
   {
    $error .= '<p class="text-danger">Only Numbers allowed in Phone</p>';
   }
   else
   {
    $mobile = clean_text($_POST["mobile"]);
   }
  }
  
  if(empty($_POST["stud_emailaddr"]))
  {
   $error .= '<p class="text-danger">Email Address is Required</p>';
  }
  else
  {
   if (!filter_var($_POST["stud_emailaddr"], FILTER_VALIDATE_EMAIL))
   {
    $error .= '<p class="text-danger">Invalid email format</p>'; 
   }
   else
   {
    $stud_emailaddr = clean_text($_POST["stud_emailaddr"]);
   }
  }
  
  if($error == '')
  {
   $stud_fname = string_convert_data('encrypt', $stud_fname);
   $stud_lname = string_convert_data('encrypt', $stud_lname);
   $mobile = string_convert_data('encrypt', $mobile);
   $stud_emailaddr = string_convert_data('encrypt', $stud_emailaddr);
   if($_POST["model_crud_opt"] == "Add")
   {
    $my_query = "
    SELECT * FROM tbl_student 
    WHERE email = '$stud_emailaddr'
    ";
    $statement = $connect->prepare($my_query);
    $statement->execute();
    $no_of_row = $statement->rowCount();
    if($no_of_row > 0)
    {
     $error = '<div class="alert alert-danger">Email Already Exists</div>';
    }
    else
    {
     $my_query = "
     INSERT INTO tbl_student (stud_fname, stud_lname, mobile, email) 
     VALUES('".$stud_fname."', '".$stud_lname."', '".$mobile."', '".$stud_emailaddr."')
     ";
     $message = '<div class="alert alert-success">Student Added</div>';
    }
   }
   if($_POST["model_crud_opt"] == "Edit")
   {
    $id = string_convert_data('decrypt', $_POST["id"]);
    $my_query = "
    UPDATE tbl_student 
    SET stud_fname = '$stud_fname', 
    stud_lname = '$stud_lname', 
    mobile = '$mobile', 
    email = '$stud_emailaddr' 
    WHERE id = '$id'
    ";
    $message = '<div class="alert alert-success">Student Edited</div>';
   }
   $statement = $connect->prepare($my_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_student');
 $statement->execute();
 return $statement->rowCount();
}

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

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

?>

You are Most welcome in my youtube Channel Please subscribe my channel. and give me FeedBack.
More Details……
Angularjs Example

Example

I hope you have Got What is Encrypt and decrypt forms with AES and RSA in PHP And how it works.I would Like to have FeedBack From My Blog(Pakainfo.com) readers.Your Valuable FeedBack,Any Question,or any Comments about This Article(Pakainfo.com) Are Most Always Welcome.