Issue
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.
Solution
STEPS:
Open the file
index.phpunder the CodeIgniter 4 application's public path/root/ci4/public.Load the
.envfile 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".envfile. It's assumed that it resides under/root/react/.env$envFileName- represents the "React application's".envfile name.\CodeIgniter\Config\DotEnv(...)->load()- this method is the one responsible for loading the.envfile 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
.envvariable 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
.envfile 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
Answered By - steven7mwesigwa Answer Checked By - Pedro (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.