Symfony 4, get .env parameter from a controller, is it possible and how?

For Symfony 5

in your .env file

APP_PARAM=paramvaluehere

in your config/services.yaml

parameters:
    app.paramname: '%env(APP_PARAM)%'

in your controller

$this->getParameter('app.paramname');

If someone is stil looking for a quick fix but not much symfonish,

define your parameter in .env

MY_PARAM='my param value'

and then in controller call it

echo $_ENV['MY_PARAM'];

if you call the varaible in the controller you better define it in the config/services.yaml under parameters section and access it through parameterBag is much symfonish way.


Did you try with:

$this->getParameter('your parameter');

Edit:

This may help you -> https://symfony.com/doc/current/components/dotenv.html


Before to user getParameter() you have to add this in services.yaml

parameters:
    your_parameter: '%env(your_parameter)%' # from .env file

  1. Add the variable in the config parameters :
    parameters:
        your_variable: '%env(YOUR_ENV_VARIABLE)%'
  1. Fetch it from the controller
    $var = $this->getParameter('your_variable');