Easiest but powerful encryption in PHP

Safety concept: Opened Padlock on digital background

For a secured system, most of the data is encrypted in server end and sent to database. And after fetching the data from database, just decrypt before showing in front end.

There are lots of procedure to encrypt the data, lots of encryption algorithm out there. But, here we will use a simple encryption method though it’s powerful 🙂

We are going to use mcrypt library of php for this method. You can install the library following the instruction below: (based on Ubuntu)

# Install the library
$ sudo apt-get install php5-mcrypt

# Move the file in correct folder
$ sudo mv -i /etc/php5/conf.d/mcrypt.ini /etc/php5/mods-available/

# Enable the library
$ sudo php5enmod mcrypt

# Restart apache
$ sudo service apache2 restart

Once you install mcrypt, you are free to use the library. Here is the code that you need to include in your project:

[gist https://gist.github.com/bappi-d-great/f5884c095b663ea90b27277f33b1e998]

The usage is already in the above gist. But again, just instantiate the class, pass the data you want to encrypt, do whatever you want. Then when needed, fetch and decrypt:

$e =  Helper_Encryption::get_instance();
$str = 'Any Data!';
$t = $e->encode( $str );
// Save $t to database after encryption

// Fetch $t from database and then decrypt
echo $e->decode( $t );

Happy coding! 🙂

Leave a comment

Your email address will not be published. Required fields are marked *