0

In the .env file there are settings of key values; for example : APP_ENV=prod

How to get the value of the key APP_ENV for example ?

steadweb
  • 15,364
  • 3
  • 33
  • 47
pheromix
  • 18,213
  • 29
  • 88
  • 158
  • Possible duplicate: https://stackoverflow.com/questions/52151783/symfony-4-get-env-parameter-from-a-controller-is-it-possible-and-how – Jovan Perovic Dec 18 '20 at 12:45
  • 3
    If you are using the Symfony framework (as opposed to individual Symfony components) then as a rule you would [inject the value into whatever class](https://symfony.com/doc/current/configuration.html#configuration-based-on-environment-variables) needs it. The syntax is a bit strange at first glance: '%env(resolve:APP_ENV)%' but you get used to it. If APP_ENV is the only value you want then it is set to a parameter already so: '%kernel.environment%' will work. Using $_ENV will work but it is not recommended for Symfony. – Cerad Dec 18 '20 at 12:56
  • @Cerad the notation is for `yaml` file – pheromix Dec 18 '20 at 13:31
  • 1
    @pheromix Sure it's for yaml. The same link shows xml and php as well. My point is that if you are using the framework then you should not be accessing env variables directly using $_ENV or getenv. You should be injecting them when they are needed. But that is fine. I suspect you will in time discover why. – Cerad Dec 18 '20 at 14:02

2 Answers2

2

See https://github.com/symfony/dotenv / https://symfony.com/doc/4.1/components/dotenv.html, which parses into $_ENV, and PHP has a getenv function which you use to get the value out of.

use Symfony\Component\Dotenv\Dotenv;

$dotenv = new Dotenv();
$dotenv->load(__DIR__.'/.env');

$appEnv = getenv('APP_ENV');
// you can also use ``$_ENV`` or ``$_SERVER``
steadweb
  • 15,364
  • 3
  • 33
  • 47
0

You can use the Dotenv() class as the documentation describe here you can call the APP_ENV like this

use Symfony\Component\Dotenv\Dotenv;

$dotenv = new Dotenv();
$dotenv->load('..\.env');
$appEnv= $_ENV['APP_ENV'];