env-in-CodeIgniter icon indicating copy to clipboard operation
env-in-CodeIgniter copied to clipboard

env() function can fail under high server load due to thread safety issues

Open anthony-n-brown opened this issue 4 years ago • 0 comments

I stumbled upon an issue in my environment where calls to env() would intermittently fail to return the expected value.

Ultimately, I root caused this to the use of getenv() within that function, which is not thread safe in PHP. Under high server load scenarios where multiple requests are being processed concurrently, I can consistently reproduce this.

I fixed this by using the following:

general_helper.php

Avoid relying on getenv() function and use one of the two other methods exposed by Dotenv.

Either:

// $value = getenv($key);
$value = $_SERVER[$key] ?? false;

Or:

// $value = getenv($key);
$value = $_ENV[$key] ?? false;

Env.php

Once the above change is made, you would no longer need the unsafe version of dotenv's create functions.

// $dotenv = Dotenv\Dotenv::createUnsafeImmutable(FCPATH);
$dotenv = Dotenv\Dotenv::createImmutable(FCPATH)

anthony-n-brown avatar Nov 17 '21 19:11 anthony-n-brown