I’m using phpfog.com for hosting and github.com for issue tracking, etc.
I have two remotes setup, one to phpfog.com, and the other to github.
In the back-end admin of phpfog you can define Environment Variables. I did so there and want to use them in my wp-config file.
Here’s the code I used:
/** Hardened Salts for use on github.com, phpfog.com, etc.*/
$AUTH_KEY = getenv('AUTH_KEY');
$SECURE_AUTH_KEY = getenv('SECURE_AUTH_KEY');
$LOGGED_IN_KEY = getenv('LOGGED_IN_KEY');
$NONCE_KEY = getenv('NONCE_KEY');
$AUTH_SALT = getenv('AUTH_SALT');
$SECURE_AUTH_SALT = getenv('SECURE_AUTH_SALT');
$LOGGED_IN_SALT = getenv('LOGGED_IN_SALT');
$NONCE_SALT = getenv('NONCE_SALT');
define('AUTH_KEY', $AUTH_KEY);
define('SECURE_AUTH_KEY', $SECURE_AUTH_KEY);
define('LOGGED_IN_KEY', $LOGGED_IN_KEY);
define('NONCE_KEY', $NONCE_KEY);
define('AUTH_SALT', $AUTH_SALT);
define('SECURE_AUTH_SALT', $SECURE_AUTH_SALT);
define('LOGGED_IN_SALT', $LOGGED_IN_SALT);
define('NONCE_SALT', $NONCE_SALT);
There must be a cleaner way of doing thisâ¦
You could make it half as long by passing the function result as a constant value without intermediate variable:
Or do that in a loop:
From WordPress 5.5.0
WordPress has added a new function for the environment variables with 3 different possible values.
You can use
wp_get_environment_type()
function to get the current environment.Usage example:
By default, if
WP_ENVIRONMENT_TYPE
is empty or invalid ( anything exceptdevelopment
,staging
&production
),production
is returned.You can define
development
orstaging
environment through thewp-config.php
file.I prefer to use this approach below:
The best way to use environment variables to control your WP environment is by using DotEnv ( https://github.com/vlucas/phpdotenv )
This approach is laid out in a blog post: https://m.dotdev.co/secure-your-wordpress-config-with-dotenv-d939fcb06e24
The basic approach is to create an .env file in the root of your site with the environment variables.
However there are a few problems with the blog post as DotEnv version 5 no longer uses environment variables by default.
So instead of the code used in the blog post, use this at the top of your wp-config.php file…
The .env file looks like this…
Defining the constants in the wp-config.php file looks like this…
Use the APP_ENV variable to switch between variable sets. For example create .env.production and .env.staging files. If the .env file does not exist then the values are pulled from the environment which works well for cloud deployment.