Storing Drupal database settings in .env file outside of webroot

Instructions for storing database credentials outside of the webroot of a Drupal project using an .env file.

Using as an example, if the ISP has assigned a home directory to the project as project_user and the webroot within the project is a folder named project_webroot. Drupal might be installed in that home directory as drupal. A symbolic link is created in /home/project_user as project_webroot --> drupal/web.

In the drupal directory, where Drupal was installed using Composer, install phpdotenv (https://github.com/vlucas/phpdotenv )

php /usr/local/bin/composer require vlucas/phpdotenv

(adjust for the method of installation and location of Composer).

Edit the settings.php file (/home/project_user/drupal/web/sites/default/settings.php) and add

$dotenv = Dotenv\Dotenv::createImmutable('../config');
$dotenv->load();

to the top of the file (line after <?php). Note that the settings.php is set to read-only by the installer, so it needs to be made writable, edited, then set back to read-only.

At the bottom of the file, locate the $databases assignment and replace with

$databases['default']['default'] = [
  'database' => $_ENV['MYSQL_DATABASE'],
  'driver' => 'mysql',
  'host' => $_ENV['MYSQL_HOSTNAME'],
  'namespace' => 'Drupal\\Core\\Database\\Driver\\mysql',
  'password' => $_ENV['MYSQL_PASSWORD'],
  'port' => $_ENV['MYSQL_PORT'],
  'prefix' => '',
  'username' => $_ENV['MYSQL_USER'],
];

Create /home/project_user/config and in that config folder, create .env with

MYSQL_DATABASE=drupal_db
MYSQL_HOSTNAME=localhost
MYSQL_PASSWORD=drupal_db_password
MYSQL_PORT=3306
MYSQL_USER=drupal_user

adjusting values as needed.

The config_sync_directory can also be moved into this new config folder, see https://www.drupal.org/docs/configuration-management/changing-the-storage-location-of-the-sync-directory .

I don’t understand why this isn’t the default, as it is normal for a symfony based application.

Reference in addition to the phpdotenv reference above, https://www.freecodecamp.org/news/the-best-way-to-manage-your-drupal-workflow-ade9525a84c0/ .