Search code examples
reactjscodeigniterenvironment-variablescodeigniter-4dotenv

How to use multiple .env files at the same time with CodeIgniter 4?


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:

    1. Open the file index.php under the CodeIgniter 4 application's public path /root/ci4/public.

    2. 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 a var_dump($_ENV) or phpinfo() (for debugging or other valid reasons) your secure credentials are publicly exposed. - Environment Variables and CodeIgniter