How to encrypt string in PHP and decrypt it and get via javascript code in single line

By yash → Wednesday, March 2, 2016
Following code is useful when you came into scenario where you want to encrypt any data using PHP and want to decrypt it and use it via JavaScript. This can be achieved by just one line of code. It will be very basic level of encryption but very useful.   Use following PHP code to encrypt any data.


<?php 
// You can encrypt any string using PHP's base64_encode function

$encryptedSting = base64_encode("your secure data");
// if you print encrypted string it will look like following sting 

echo $encryptedSting;
// Result - "eW91ciBzZWN1cmUgZGF0YQ=="
?>


In JavaScript there are two functions respectively for decoding and encoding base64 strings.
  • atob()
  • btoa()
Now once the String is encrypted, you can decrypt it by using atob() function.

<script type="text/javascript">
 // Let's say now you have encrypted sting.
 // just use atob()  function to decrypt previously encrypted data

var decryptedData  = atob("eW91ciBzZWN1cmUgZGF0YQ==");

// check you output in console
Console.log(decryptedData);

</script>
YEAH!! THAT's IT.
Yashwant Patel

No Comment to " How to encrypt string in PHP and decrypt it and get via javascript code in single line "