Sign Up |

PHP Encrypt/Decrypt Snippet

(3 posts) (2 voices)
  1. Monjurul Dolon Posted 1 year ago #

    While working on my WordPress theme framework, I came across the need to encrypt and save an array to a file, then later load and decrypt it. Here it is, in case anyone needs something like this:

    define("SALT","my_secure_salt");
    $array = array('this','is','an','array');
    $filename = 'test.txt';
    
    // Save
    $output = encrypt(serialize($array));
    $file = fopen($filename, 'w+');
    fwrite($file, $output);
    fclose($file);
    
    // Load
    $new_array = unserialize(decrypt(file_get_contents($filename)));
    print_r($new_array);
    
    // Functions
    function encrypt($text){
        if(function_exists(mcrypt_encrypt))
            return trim(base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, SALT, $text, MCRYPT_MODE_ECB, mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB), MCRYPT_RAND))));
        else
            return base64_encode($text);
    }
    
    function decrypt($text){
        if(function_exists(mcrypt_encrypt))
            return trim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, SALT, base64_decode($text), MCRYPT_MODE_ECB, mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB), MCRYPT_RAND)));
        else
            return base64_decode($text);
    }
    
  2. tomsbabyjenna Posted 1 year ago #

    what exactly is this encrypt thing and in what circumstance would someone need to use it? Is framework the basics to a website?

  3. Monjurul Dolon Posted 1 year ago #

    Good question Jenna! It's actually used for storing data you need to use later but you don't want other people to be able to read.

    For example, you could use this to store your diary entries. It will take your diary entry and turn it into crazy looking random code that no one else will understand. Since you have the password for it, you can decrypt it later to be able to read it.


Reply

You must log in to post.

© Copyright 2010 DevGrow - Design. Develop. Grow. 20 queries. 0.34 seconds.