19

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…

Abraham
  • 8,525
  • 5
  • 47
  • 53
Robert C Edwards
  • 708
  • 2
  • 8
  • 17

5 Answers5

24

You could make it half as long by 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));
}
DiskJunky
  • 4,750
  • 3
  • 37
  • 66
zerkms
  • 249,484
  • 69
  • 436
  • 539
14

I prefer to use this approach below:

<?php

//GET HOSTNAME INFO
$hostname = $_SERVER['SERVER_NAME']; 

//VERIFY WHICH ENVIRONMENT THE APP IS RUNNING
switch ($hostname) {
    case 'development.dev':
        define('WP_ENV', 'development');
        define('WP_DEBUG', true);
        break;
    case 'staging.mywebsite.com':
        define('WP_ENV', 'staging');
        define('WP_DEBUG', true);
        break;
    case 'www.mywebsite.com':
        define('WP_ENV', 'production');
        define('WP_DEBUG', false);
        break;
    default:
        define('WP_ENV', 'production');
        define('WP_DEBUG', false);
}

?>
ksav
  • 20,015
  • 6
  • 46
  • 66
Oscar Alencar
  • 149
  • 1
  • 2
  • I like this and would suggest separating seach env into it's own file and then `include` them here, esp if you use git and code review system. Keeps things tidy. – Sgnl Dec 09 '21 at 00:18
  • this works if your environments follow those specific urls and you don't have devs adding a specific one in their `/etc/hosts` file for local testing. make sure server names are set & predictable. I also prefer to use things like `defined( 'WP_DEBUG' ) || define( 'WP_DEBUG', true );` to avoid double defining or overriding higher up – Sandra Jul 24 '23 at 12:32
14

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:

If(wp_get_environment_type() === 'development') {
 // do something
} else {
 // do something
}

By default, if WP_ENVIRONMENT_TYPE is empty or invalid ( anything except development, staging & production), production is returned.

You can define development or staging environment through the wp-config.php file.

define( 'WP_ENVIRONMENT_TYPE', 'development' );
Ashish Yadav
  • 1,901
  • 2
  • 17
  • 23
  • 1
    A side note: I am using https://localwp.com/ and by default, I noticed it define the value with 'local' – Amr Dec 17 '22 at 23:41
  • 1
    A side note: defining the variable with any value other than the exact 4 possible values won't change the value. Possible values are ‘local’, ‘development’, ‘staging’, and ‘production’. – Amr Dec 17 '22 at 23:54
4

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...

$app_env = getenv("APP_ENV");
$file = $app_env == null ? ".env" : ".env.".$app_env;
if(file_exists(__DIR__.'/'.$file))
{
    require_once(__DIR__ . '/vendor/autoload.php');
    (Dotenv\Dotenv::createUnsafeImmutable(__DIR__,$file))->load();
    error_log("Environment loaded from ".$file);
} else {
    error_log("*WARNING* environment file not found: ".$file);
}

The .env file looks like this...

# MySQL settings

DB_NAME=wpbench
DB_USER=wpuser
DB_PASSWORD=password
DB_HOST=localhost
DB_CHARSET=utf8
DB_COLLATE=

Defining the constants in the wp-config.php file looks like this...

/** The name of the database for WordPress */
define( 'DB_NAME', getenv('DB_NAME'));

/** MySQL database username */
define( 'DB_USER', getenv('DB_USER'));

/** MySQL database password */
define( 'DB_PASSWORD', getenv('DB_PASSWORD'));

/** MySQL hostname */
define( 'DB_HOST', getenv('DB_HOST'));

/** Database Charset to use in creating database tables. */
define( 'DB_CHARSET', getenv('DB_CHARSET'));

/** The Database Collate type. Don't change this if in doubt. */
define( 'DB_COLLATE', getenv('DB_COLLATE'));

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.

AQuirky
  • 4,691
  • 2
  • 32
  • 51
  • thanks for the link. It needs a little touchup, specially regarding the use of `getenv('ENV_KEY')`, it should be replaced with `$_SERVER['ENV_KEY']`. – tsega Dec 17 '20 at 06:07
  • 2
    @tsega I struggled with this very issue. I decided to go with get_env() despite the deprecation in DotEnv docs that environment variables are not thread safe. Thread safety does not matter if the environment variables don't change. And they shouldn't change...they are part of the static configuration. You need environment variables to configure WP on cloud services such as Azure. – AQuirky Dec 17 '20 at 14:53
  • how it's work on admin side, in my term front-end side is work but when i go to login then i get error. no env – Noor Fahad May 17 '23 at 10:52
2

You could try this:

-Add a ".env" file to the root folder and add your secret variables

DB_NAME=my_db_name
DB_USER=root
DB_PASSWORD=root
DB_HOST=localhost

-Update wp-config.php to have this

$env = [];
if( file_exists( '.env' ) && count( parse_ini_file( '.env' ) ) > 0 ) {
    $env = parse_ini_file( '.env' );
} else {
    echo "no env";
    exit;
}

define( 'DB_NAME', $env['DB_NAME'] );
define( 'DB_USER', $env['DB_USER'] );
define( 'DB_PASSWORD', $env['DB_PASSWORD'] );
Abdullah Aman
  • 1,314
  • 11
  • 11