How to Encrypt a File in PHP
Files (or any other stream of data) can be encrypted by PHP using the MCrypt module. It is not normally installed by default with PHP, but it is available through the standard PHP library repository, CPAN. It provides dozens of encryption algorithms, including 3DESm, BLOWFISH, and RC6.
Instructions
-
-
1
Create a new text file using any text editor you like, provided it is capable of writing plain text. For example, Windows Notepad and NANO are acceptable, but Open Office and Microsoft Word are not, since they do not, by default, write plain text files.
-
2
Save the file with the name "encrypt.php".
-
-
3
Paste the following code within it:
<?php
$key = "a secret key";
$f = fopen("file.csv", "r");
$input = fread($f, filesize($f));
$encrypted_data = mcrypt_ecb (MCRYPT_3DES, $key, $input, MCRYPT_ENCRYPT);
print $encrypted_data;
?>
This code first opens a file named "file.csv," and reads the data from it. The data is then encrypted using a key. In this case, the key is "a secret key," and is stored in the $key variable. Be sure to change the file name in the "$f = fopen("file.csv", "r");" line to reflect the file name you would like to encrypt and the key to a suitable key. Anyone that knows the key can unlock the file, so it should be difficult to guess. Finally, it prints the encrypted data to standard out (the terminal).
-
1
Tips & Warnings
If MCrypt is not installed, it can be installed using the CPAN repository by typing the following command into a terminal:
cpan MCrypt
References
- Photo Credit padlocks image by Christopher Hall from Fotolia.com