'Symfony6: Set/update/manipulate environment variables (APP_ENV) with PHP (bootstrap.php)
We are in the process of reworking a Symfony5 application to Symfony6. We have a special case where the environment APP_ENV is dependent on the hostname of the app.
Accessing the same app via app1.domain.com and app2.domain.com should set the APP_ENV variable for symfony to prod1 or prod2.
This used to happen in the config/bootstrap.php (a relic from Symfony4), but this is no longer available in Symfony6.
Where is the best update-save place to inject some code to switch the variable before Symfony starts processing requests?
The old portion in bootstrap.php looked something like this:
if(isset($_SERVER['HTTP_HOST'])) {
if(preg_match('#^app1\.domain\.com$#',$_SERVER['HTTP_HOST'])) {
$_SERVER['APP_ENV'] = "prod1"; $_ENV['env_name'] = "prod1";
$_ENV['env_name'] = "production_client1";
} elseif(preg_match('#^app2\.domain\.com$#',$_SERVER['HTTP_HOST'])) {
$_SERVER['APP_ENV'] = "prod2"; $_ENV['env_name'] = "prod2";
$_ENV['env_name'] = "production_client2";
} elseif(preg_match('#^app\.dev\.local$#',$_SERVER['HTTP_HOST'])) {
$_SERVER['APP_ENV'] = "dev"; $_ENV['env_name'] = "dev";
$_ENV['env_name'] = "development";
} else {
die("invalid domain");
}
}
Further switching happens within the app depending on the environment.
The following approaches do/did NOT work:
- setting the environment variable on the server (shared hosting) is not possible
- setting it via .htaccess does not work because mod_rewrite prepends REDIRECT_ to all environment variables
- subscribers/listeners only attach at the request event (kernel.request), which is too late
- setting it in .env is static
- setting it in .env.local.php is not update save, as this file is generated
- running a file as a imported resource (imports) in config.yaml is also does not seem to work
This question is explicitly about switching the environment, not necessarily about a workaround! A nice bonus feature of this was that the same code could be run in the dev environment on the server just by accessing it via the local dev domain.
Solution 1:[1]
The solution we went with was to put the switching code into an include file in config/ and load it directly from index.php before loading autoload_runtime.php and before creation of the kernel. Thank you to @Cerad for ensuring us that this would probably be ok.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | MVKS |
