I use the standard .env
file with CodeIgniter 4. In addition, I want to use some information from a React application that is hosted on the same server.
How can I use /root/ci4/.env
together with /root/react/.env
so that I can use getenv('REACT_APP_FOO');
in my application?
The REACT_APP_*
variable names will not exist in the /root/ci4/.env
file, for sure.
CodePudding user response:
STEPS:
Open the file
public/index.php
under the CodeIgniter 4 application root path/root/ci4
.Load the
.env
file of the React application just before the line of code$app->run();
in the file/root/ci4/public/index.php
:
// ...
// Load environment settings from .env file into $_SERVER and $_ENV
$envPath = ROOTPATH . ".." . DIRECTORY_SEPARATOR . "react";
$envFileName = ".env";
if (is_file($file = $envPath . DIRECTORY_SEPARATOR . $envFileName) && is_readable($file)) (new \CodeIgniter\Config\DotEnv($envPath, $envFileName))->load();
// ...
Where:
$envPath
- represents the directory path of the "React application's".env
file. It's assumed that it resides under/root/react/.env
$envFileName
- represents the "React application's".env
file name.\CodeIgniter\Config\DotEnv(...)->load()
- this method is the one responsible for loading the.env
file and processing it so that we end up with all settings in the PHP environment vars (i.e.getenv()
,$_ENV
, and$_SERVER
).
Extra Notes:
A.
If a
.env
variable already exists in the environment, it will NOT be overwritten. - Environment Variables and CodeIgniter
This means that an environment variable defined under /root/react/.env
won't overwrite a similar one defined under /root/ci4/.env
.
B.
WARNING: Note that your settings from the
.env
file are added to Environment Variables. As a side effect, this means that if your CodeIgniter application is (for example) generating avar_dump($_ENV)
orphpinfo()
(for debugging or other valid reasons) your secure credentials are publicly exposed. - Environment Variables and CodeIgniter