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

All we need is an easy explanation of the problem, so here it is.

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.

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1


  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();

// ...


  • $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:


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.


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

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply