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??
You are defining same
DB_NAME
constant for database user name, password and host change the constantsTry like this
Or you can create .htaccess file where you will say
SetEnv DB Abc;
and in php echo DB;
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
:The correct way is by referencing the right path before the file. Like so:
This ended up solving my problem when I called environment variables like so:
You can also set variables using the
php.ini
file. In some shared hostings (like uberspace) you have a specialphp.d
folder with custom ini files.This is how your
wordpress.ini
file could look like:And this is how you can access it in
wp-config.php
: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:
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.