A customer recently asked about setting various WordPress environment variables from a separate file (ie not directly in the WordPress config). I found an article which seems to be a reasonable solution: Using an .env file for database and other credentials with WordPress & WooCommerce
The steps to adapt that procedure for use at Opalstack are:
- Install WordPress if you've not done so already.
- Log in to SSH as your WordPress app's shell user.
- Run the following commands to install composer:
cd ~
mkdir -p ~/bin
wget -O composer-setup.php https://getcomposer.org/installer
php composer-setup.php --install-dir=$HOME/bin --filename=composer
rm composer-setup.php
export PATH=$HOME/bin:$PATH
- Run the following commands to install the PHP dotenv package, replacing "name_of_app" with the name of your WordPress app:
cd ~/apps/name_of_app
composer require vlucas/phpdotenv
touch .env
chmod 600 .env
- Edit the file
.env
(that's a dot followed by "env") in your WordPress app directory with the variables that you want to define. For example if you want to keep your WordPress database credentials in the .env
file then you would add the following, replacing "your_db_name" etc with your own credentials:
DB_NAME=your_db_name
DB_USER=your_db_user
DB_PASSWORD=your_db_password
- Edit
wp-config.php
to add the following lines at the top of the file, just after the opening <?php
tag:
if ( ! defined( 'ABSPATH' ) ) {
define( 'ABSPATH', __DIR__ . '/' );
}
require_once ABSPATH . 'vendor/autoload.php';
$dotenv = Dotenv\Dotenv::createImmutable(ABSPATH);
$dotenv->load();
- Edit
wp-config.php
further to set your environment variables by altering the existing define
statements or adding new ones as needed. For example, to use the database credentials that we defined earlier you would change these lines...
/** The name of the database for WordPress */
define( 'DB_NAME', 'your_db_name' );
/** Database username */
define( 'DB_USER', 'your_db_user' );
/** Database password */
define( 'DB_PASSWORD', 'your_db_password'
...to this:
/** The name of the database for WordPress */
defined('DB_NAME') or define('DB_NAME', $_ENV['DB_NAME']);
/** Database username */
defined('DB_USER') or define('DB_USER', $_ENV['DB_USER']);
/** Database password */
defined('DB_PASSWORD') or define('DB_PASSWORD', $_ENV['DB_PASSWORD']);
At that point you're done - your WordPress app is now reading its database credentials from an environment file.
Note: if you are managing your files in git then you should add the .env
file to your .gitignore
file.