Encrypt files in PHP

Have you ever think of encrypting your secret files yourself? If you dunno how to do it yourself, here’s the rescue! In this article, I’ll teach you how to encrypt/decrypt files entirely in PHP!

First, please make sure Mcrypt is with your PHP bundle. If you don’t have this extension, please install it first as we need this to encrypt/decrypt files.

Then, it’s time to code! The code is pretty short as it uses the Mcrypt stream filter which also brings a huge performance increase when handling large files.

This is the code that encrypt contents written into the files. Isn’t this pretty short?┬áBut, how can I make the contents readable again? Here’s the way to decrypt the files:

Now we have a nice and easy solution to keep things secret in PHP. (Just to make sure, you need to change $passphrase into your very own password and keep it secret.)

Published by

Licson Lee

Hi! I'm Licson. I'm a student who loves programming.

6 thoughts on “Encrypt files in PHP”

  1. Hi Licson,
    I am not that much familiar with file encryption/decryption in php,
    I just want to know, Is it possible to encrypt/decrypt PDF file content using above code?
    Please guide me on this.
    Thank you.

    1. Any file is encrypted in the same manner. This method will work for any file. However, if your PHP gets exposed, intruders will be able to see your encryption key. It is much safer to do the encryption serverside. If your server is running linux, you can use openssl.

Leave a Reply to g. bowser Cancel reply

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