vlucas / phpdotenv

Loads environment variables from `.env` to `getenv()`, `$_ENV` and `$_SERVER` automagically.
BSD 3-Clause "New" or "Revised" License
13.15k stars 626 forks source link

Adapterrepository.php -> get returns sometimes null #573

Closed susanne99 closed 1 month ago

susanne99 commented 1 month ago

i use laravel 11 on WIN11 in XAMPP Environment. With laravel 10 i had no problems. but after upgrade it happens sometimes, that he read null from the config settings. not only the app_key, other config settings also. i debugged a little bit, and see that this function in adapterrepository.php returns sometimes null, that means it is very instabil the strange thing is, the production is an debian with apache and it works there without problems. but anyway, there must be a "bug", or what do you thing ?

in the $this->reader there are 3 readers in - is that okay ?? Dotenv\Repository\Adapter\MultiReader {#48 -readers: array:3 [ 0 => Dotenv\Repository\Adapter\ServerConstAdapter {#26} 1 => Dotenv\Repository\Adapter\EnvConstAdapter {#25} 2 => Dotenv\Repository\Adapter\PutenvAdapter {#27} ] }

the echo line is from me for debugging purpose only

`public function get(string $name) { if ('' === $name) { throw new InvalidArgumentException('Expected name to be a non-empty string.'); }

    ****if ($name == "APP_KEY"){
        echo "sdasdasd  -> " . $this->reader->read($name)->getOrElse(null);
    }****

    return $this->reader->read($name)->getOrElse(null);
}`
GrahamCampbell commented 1 month ago

This is a known issue with putenv and getenv. They are not thread safe, and concurrent calls can corrupt memory. I'd recommend removing PutenvAdapter.

GrahamCampbell commented 1 month ago

See https://github.com/vlucas/phpdotenv?tab=readme-ov-file#putenv-and-getenv.

susanne99 commented 1 month ago

Hello, great, finally someone who knows his stuff. laravel uses these functions, not me!! how can I remove the PutenvAdapter adapter? If only via Laravel, right?

GrahamCampbell commented 1 month ago

With Laravel, you should never be using env directly in your code. Only put env in your config files, and then run the config:cache command. This means that your app doesn't actually call these functions at runtime, and you are never using these functions in a threaded context.

GrahamCampbell commented 1 month ago

This is somewhat subtext in their docs, but they do point out that the env file is not loaded when config is cached: https://laravel.com/docs/11.x/configuration#configuration-caching.

GrahamCampbell commented 1 month ago

It is also possible to tell Laravel to not use putenv and getenv. See https://github.com/laravel/framework/blob/v11.23.5/src/Illuminate/Support/Env.php#L26-L46; https://github.com/laravel/framework/pull/28908; https://github.com/laravel/framework/pull/28740.