Skip to content
Advertisement

Using Environment variables in WordPress wp-config

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…

UPDATE! Here’s the cleaned up code thanks to zerkms

$dbvalues = array('DB_HOST', 'DB_NAME', 'DB_USER', 'DB_PASSWORD');
/** -------------------------------------------------------------*/
foreach ($dbvalues as $dbvalue) {
    define($dbvalue, getenv($dbvalue));
}

$saltykeys = array('AUTH_KEY', 'SECURE_AUTH_KEY', 'LOGGED_IN_KEY', 'NONCE_KEY', 'AUTH_SALT', 'SECURE_AUTH_SALT' , 'LOGGED_IN_SALT', 'NONCE_SALT' );
/** -------------------------------------------------------------*/
foreach ($saltykeys as $saltykey) {
    define($saltykey, getenv($saltykey));
}

Advertisement

Answer

You could make it twice shorter passing the function result as a constant value without intermediate variable:

define('AUTH_KEY', getenv('AUTH_KEY'));

Or do that in a loop:

$vars = array('AUTH_KEY', 'SECURE_AUTH_KEY', ...);
foreach ($vars as $var) {
    define($var, getenv($var));
}
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement