Store WordPress environment variables in a separate file
Load your environment variables from a separate dot file to keep them secure and environment specific
WordPress stores its environment variables in its wp-config.php file. Since this file is required for WordPress to operate, it’s common for it to be committed to code repositories along with the rest of the site code. However, this wp-config.php file will often contain sensitive information such as database connection credentials that you may want to keep secret.
One solution to this is to store the sensitive environment variables in a separate file, in the style of the DotEnv PHP library.
Separating the site credentials from wp-config.php and storing them in a standalone file also has an advantage when you’re working between multiple environments such as local, staging and production. You can store the correct credentials for the environment in question within this file and not worry about conflicts in the repository as changes are pushed.
Since it’s the MySQL database credentials we’re concerned with for now, we’re just going to replace the following lines of wp-config.php:
// ** MySQL settings - You can get this info from your web host ** // /** The name of the database for WordPress */ define( 'DB_NAME', 'wp_sitename' ); /** MySQL database username */ define( 'DB_USER', 'dbuser' ); /** MySQL database password */ define( 'DB_PASSWORD', 'dbpass' ); /** MySQL hostname */ define( 'DB_HOST', 'localhost' ); /** Database Charset to use in creating database tables. */ define( 'DB_CHARSET', 'utf8' ); /** The Database Collate type. Don't change this if in doubt. */ define( 'DB_COLLATE', '' );
We copy the lines above defining the DB_NAME, DB_USER, DB_PASSWORD and other constants into a new file called .env.php which is placed in the website root. The above lines of wp-config.php are then replaced with the following include, bringing those environment variables back into our site.
// ** MySQL settings - You can get this info from your web host ** // /** The name of the database for WordPress */ include '.env.php';
Finally, we add .env.php to our .gitignore file to ensure it does not get committed to our code repository.
You can add further environment variables such as API keys to this file in order to keep them secret and environment specific.
A lightweight, intuitive WordPress theme to enable flexible developement.
- Lighting-fast installer
- Intuitive SASS structure