Securing PHP Environment Variables for Production Use

Having a plain-text environment file on a production server just feels like you’re already exposed even if it’s outside a public directory.What if we could encrypt our environment file and decrypt it in our project whenever we need to access our sensitive data..I’ll show you how to use the secure-env-php library I wrote to encrypt your .env files.Secure Env PHPYou’ll need to download secure-env-php by using Composer in your project’s root directory.composer require johnathanmiller/secure-env-phpIf you haven’t created an .env file already, let’s do it now..Inside your project’s root directory enter the command touch .env..Open it up and enter in things such as database credentials, API keys, etc.Such as the example below.DB_HOST=localhostDB_USER=usernameDB_PASS=passwordAfter you’ve entered in your data, save the file and now we can go ahead and get to the fun part.EncryptionI’ve included a PHP script inside Composer’s vendor/bin directory that can be executed in the terminal to walk you through the steps to encrypting your environment file.To run this script, type the following: vendor/bin/encrypt-envThe first prompt will ask for the path to your .env file..You may notice in square brackets it will say .env..This is the default suggestion..If your environment file is located in your project root you can press enter and continue..If not, then enter the direct or relative path to your environment file.Second prompt will ask you for a secret key..In the square bracket I’ve generated a random string for you to use or you may enter your own secret..Don’t forget to copy the string for decrypting the encrypted environment file later.In the third prompt, you can accept the default algorithm aes256 or you can enter a different algorithm that’s supported by the openssl_encrypt function..Here’s a list of supported algorithms.Finally, the last prompt will suggest the path and file name to save your encrypted environment file..It will normally be the same path as your unencrypted file, but with .enc appended to the end of the name.. More details

Leave a Reply