Create files with encrypted and decrypted data from a file in PHP

By IncludeHelp Last updated : January 7, 2024

Problem statement

Given a file, write PHP code to create files with encrypted and decrypted data from the given file.

Let's suppose, there is an input file named "original_file.txt" containing string, you have to encrypt and decrypt the data of the "original_file.txt" and save it into two different files "encrypted_file.txt" and "decrypted_file.txt".

Creating files with encrypted and decrypted data from a file

To encrypt the string, use the openssl_encrypt() function, and to decrypt the string, use the openssl_decrypt() function. To create separated files with encrypted and decrypted data, first, read the file's data, encrypt it, and save encrypted data to a file and then read the file having encrypted data, decrypt its content, and save the encrypted data to another file.

PHP code to create files with encrypted and decrypted data from a file

<?php
// Function to encrypt the given file
function encryptFileContent($in_file, $out_file, $key)
{
    $file_content = file_get_contents($in_file);
    $encrypted_content = openssl_encrypt(
        $file_content,
        "aes-256-cbc",
        $key,
        0,
        $key
    );
    file_put_contents($out_file, $encrypted_content);
}

// Function to decrypt an encrypted file
function decryptFileContent($in_file, $out_file, $key)
{
    $file_content = file_get_contents($in_file);
    $decrypted_content = openssl_decrypt(
        $file_content,
        "aes-256-cbc",
        $key,
        0,
        $key
    );
    file_put_contents($out_file, $decrypted_content);
}

//Main Code
$encryption_key = "IncludeHelp12345";
$original_file = "original_file.txt";
$encrypted_file = "encrypted_file.txt";
$decrypted_file = "decrypted_file.txt";

encryptFileContent($original_file, $encrypted_file, $encryption_key);
decryptFileContent($encrypted_file, $decrypted_file, $encryption_key);
?>

Output

The output of the above program is:

Content of original file (original_file.txt):
Hello, world! How are you?

Content of encrypted file (encrypted_file.txt):
+IupZfksNh/ZQ0aPpYRrEnmt9/6Oy0j+CTpR79dVGK4=

Content of decrypted file (decrypted_file.txt):
Hello, world! How are you?
Note

Here, we used "IncludeHelp12345" as the value of the encryption key, you can change it based on your requirements. We used the "aes-256-cbc" cipher method, you can choose other cipher methods also. To know more about the cipher methods that you can use in PHP, visit: openssl get cipher methods Manual.

More PHP File Handling Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.