Securing keys with DotEnv 5.2 using Composer in WordPress

Storing access keys is an integral part of development. Secure key storage becomes critical with multiple environments such as staging, development, and production. Specifically for WordPress, the key concerns are not disclosing keys in version control and securing the wp-config.php file. 

While there are multiple ways to do this, key storage becomes simple with DotEnv using Composer. In this post, we’ll take a look at the uses of DotEnv using Composer in WordPress.

Let’s begin by installing the vlucas/phpdotenv package using Composer.

Step 1

WordPress commonly exists in the htdocs folder in a local environment (using XAMPP or MAMP). Switch to this directory or the root directory where WordPress exists. Enter the following commands,
with basic arguments such as the name and description,

Composer init
DotEnv in wordpress 1

The above command creates the composer.json file in the root directory.

You can also create the composer.json file as shown below,

DotEnv in wordpress 2

Note: We’ve installed the latest version, 5.2, of vlucas/phpdotenv.

Step 2

After creating a composer.json file, enter the following command,

composer install
DotEnv in wordpress 3

This command creates the vendor directory with the required packages and their dependencies.

Step 3

Now let us create the .env file as below in the WordPress root directory (in my case, it is in the ‘htdocs’ folder) with secret keys or variables needed for the project.

DotEnv in wordpress 4

We are now nearing the finish line. 

Step 4

Each time you wish to use DotEnv environment variables, you can add the following code at the beginning of the file. 

DotEnv in wordpress 5

For example, if you wish to use these environment variables in the WordPress wp-config.php file, then you should add the above code to the top of the file as follows,

You can access the environment variables DB_NAME using $_ENV[‘DB_NAME’] in any PHP file in the above code.

Step 5

This is the last step where the .env file is added to your .gitignore file. This addition prevents disclosure in the repository or version control.

Leave a Comment

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

About the author

Gurushant Upase

Gurushant has more than a decade of development experience across a variety of domains and languages. He has a Masters degree in Computer Science from Pune University and is a Lead Software Developer at Synerzip.

Talk to us

Scale your engineering team, decrease time to market and save at least 50 percent with our optimized Agile development teams.

Contact us