I'm having this strange issue on php7.4 and php8.1 on windows11 (apache2.4) where my craft sites loose or fail to load the .env data on some requests and only when under load / handling requests in very fast succession.
I have recorded a video that demonstrates the issue, its about 5 minutes, if anyone can peep this and let know if you have any idea what is going on I'm all ears.
The crux of the issue is that when this problem occurs a 503 is returned because during the bootstrap the craft code is checking if its "installed" by checking the database connection which fails due to the database configuration not being loaded "randomly" on some requests.
My first thought is this has something to do with opcache and it not including the file each time, but I'm not sure why opcache would ever have a version of this file cached where the values were false. Also, I checked my phpinfo() ouptut and the only reference to opcache is the module authors section and its clearly not enabled in my ini file.
I think I solved this and this boils down to an low-level apache MPM issue. I was reading this thread here: https://laracasts.com/discuss/channels/general-discussion/laravel-intermittently-does-not-pull-from-environment-variables-correctly (I know its laravel but the problem is pretty much identical). I use php-fpm on the server so this problem does not occur there so I'm going keep my .env file and load that for '*' and then I'm adding a 'dev' sub-config with the dev server config hard coded to the config file and I'm pretty sure this will fix it.
The only problem I'm foreseeing here is that I use custom $ENV_VARS for some of my config stuff and I'm not sure how I'm going to deal with that on my local machine and if the code cannot read the
ENVIRONMENT variable from the .env I'm not sure how it's going to know it's in 'dev' mode when the problem occurs. I guess I'll have to hard-code something in the
/web/index.php file based on the PHP_OS constant or something instead of reading the environment... at least as a fallback.
I'll report back if this fixes the issue for me. I'm still posting all of this as a matter of record, in case someone else runs into this.
So my described "workaround" does work as I had hoped but Andrew below dropped the
App::env() bomb on me just now so I'm gonna try that next and if that works then that is the answer. I'm guessing at some point craft shipped with
getenv() in the config and was later changed to use this wrapper static method, probably to work around problem (maybe anyway). I will report back and accept his answer after I try it out.