4

I am trying to pass environment variables to settings.php file for database configurations in Drupal, I am able to access the environment variables and store them to variables and pass those variables to database array in settings.php

If i print the array to console it prints fine, but while accessing the website Apache log gives below error

I have tried directly passing env variable using getenv() Passing the env variable to another variable and passing that new variable to database array Converting the Variable to UTF-8 encoding and passing it to database array

If I hardcode the database configuration values it works fine, but when I try to read it through env variable it does not work! I am not able to understand why is not working when the values passes seem to be ok

Error Log Stack

Drupal\\Core\\Database\\DatabaseAccessDeniedException: SQLSTATE[HY000] [1045] Access denied for user ''@'localhost' (using password: NO) in /var/www/html/core/lib/Drupal/Core/Database/Driver/mysql/Connection.php on line 427

Code in Settings.php

$vars = array(
  'DB_HOST',
  'DB_USERNAME',
  'DB_PASSWORD',
  'DB_PORT'
);
foreach($vars as $var) {
  if(!isset($_ENV[$var]) && getenv($var)){
    $_ENV[$var] = getenv($var);
  }
}

$username = mb_convert_encoding($_ENV['DB_USERNAME'], "UTF-8");
$password = mb_convert_encoding($_ENV['DB_PASSWORD'], "UTF-8");
$host = mb_convert_encoding($_ENV['DB_HOST'], "UTF-8");
$port = mb_convert_encoding($_ENV['DB_PORT'], "UTF-8");

$databases['default']['default'] = array (
  'database' => 'a_16a7f4a6-74a2-4066-aaa6-c0f4029f9a9f',
  'username' => $username,
  'password' => $password,
  'prefix' => '',
  'host' => $host,
  'port' => $port,
  'namespace' => 'Drupal\\Core\\Database\\Driver\\mysql',
  'driver' => 'mysql',
);
print_r($databases);

Output when I just run the php file it displays

Array
(
  [default] => Array
    (
        [default] => Array
            (
                [database] => a_16a7f4a6-74a2-4066-aaa6-c0f4029f9a9f
                [username] => root
                [password] => root
                [prefix] => 
                [host] => localhost
                [port] => 3306
                [namespace] => Drupal\Core\Database\Driver\mysql
                [driver] => mysql
            )

    )

)
Comsciers
  • 154
  • 11

0 Answers0