I am allowing a user to download a backup of their mysql database in an encrypted file, so that the user can archive these files. I have built a restore script which allows a user to upload an encrypted file, and, if valid, restore the database to whatever is contained in that mysql dump.

The part I am having a little trouble with is using mcrypt to encrypt the file. I have successfully built the system I have described above (with all major checks in place), but to encrypt and unencrypt the file, I end up reading the entire thing into a buffer and encrypting it character by character:

PHP Code:
                        $theFile file_get_contents($filepath.$filename);
$fh fopen($filepath.$filename,'w');
($encryption is an instance of an encryption class I have which encrypts whatever is passed to the encrypt function with $key).

It's not too bad because the backup is gzipped before it is downloaded (and after it is uploaded) so right now, it is still quite small (only about 20Kb for a MySQL dump of ~120Kb). But if and when the files get larger, this can take up quite a bit of time. I was doing some testing and decided to upload an 'invalid' backup file (it was some random jpeg on my computer ~600Kb) and it took 7 or 8 seconds which may not be too long, but when the file gets up around 3 or 4 mbs, I'd imagine this would start to take a long time....

How can I encrypt a file without reading the whole thing into memory and encrypting it character by character?