avaj
avaj

Reputation: 309

Error Connecting Database: Using Environment Variables into wp-config.php

I want to configure a wordpress site for which my wp-config should take database values from Environment variables. I have set my environment variables but during it shows "Error establishing a database connection".

here is the code i am using

define('DB_NAME', getenv('DB'));
define('DB_USER', getenv('us'));
define('DB_PASSWORD', getenv('pa'));
define('DB_HOST', getenv('end'));

I have tried it running from terminal as well but error is same. I am not able to figure out what is causing this problem.

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Database Error</title>

</head>
<body>
    <h1>Error establishing a database connection</h1>
</body>
</html>

Is their something being missed??

Upvotes: 2

Views: 5103

Answers (4)

NicoHood
NicoHood

Reputation: 1123

You can also set variables using the php.ini file. In some shared hostings (like uberspace) you have a special php.d folder with custom ini files.

This is how your wordpress.ini file could look like:

WP_DB_NAME=example
...

And this is how you can access it in wp-config.php:

...
define( 'DB_NAME', get_cfg_var('WP_DB_NAME') );
...

Make sure to reload the php config. This is somewhat special to your provider, I could also imagine that they reload it every 5 minutes or so. On uberspace you can do it with:

uberspace tools restart php

Sadly not all hosting providers give you that much freedom. However this was a nice way for me to place the configuration somewhere outside the folder where all my wordpress files are. Then I can safely backup them without exposing the database password in the backup.

Upvotes: 0

LatentDenis
LatentDenis

Reputation: 2991

I was receiving the same error. It looked like my wp-config.php was being called twice from two different locations. The way I was referencing my .env file was incorrect.

If you're doing anything similar to this in your wp-config.php:

$dotenv = Dotenv\Dotenv::create(__DIR__);
if(file_exists(".env")) {
    $dotenv->load();
}

The correct way is by referencing the right path before the file. Like so:

$dotenv = Dotenv\Dotenv::create(__DIR__);
if(file_exists($_SERVER['DOCUMENT_ROOT'] . '/' . '.env')) {
    $dotenv->load();
}

This ended up solving my problem when I called environment variables like so:

define( 'DB_HOST', getenv('DB_HOST') );

Upvotes: 0

jeet
jeet

Reputation: 27

Or you can create .htaccess file where you will say SetEnv DB Abc; and in php echo DB;

Upvotes: 0

Vidya L
Vidya L

Reputation: 2314

You are defining same DB_NAME constant for database user name, password and host change the constants

Try like this

define('DB_NAME', getenv('DB'));
define('DB_USER', getenv('us'));
define('DB_PASSWORD', getenv('pa'));
define('DB_HOST', getenv('end'));

Upvotes: 0

Related Questions