skip to Main Content

I wanna get app/etc/env.php variables in Magento 2 inside php code.

how is it possible?

for example I wanna something like this:

<?php
echo $_ENV['db']['host'];
?>

I mean I need to get the host that had been set in the env.php file.

2

Answers


  1. You have to declared the values for that env param first.

    You can do it in the *.php file like that:

    $_ENV["MY_ENV_VALUE"] = "value";
    $value = $_ENV["MY_ENV_VALUE"];
    

    If your’re using apache declare env in .htaccess like that:

    SetEnv MY_ENV_VALUE "value"
    

    If you’re using nginx you need to use fastcgi_params and set variables_order = "EGPCS" in your php.ini file.

    fastcgi_param MY_ENV_VALUE "value"
    
    Login or Signup to reply.
  2. Found the answer here: Magento 2. Retrieve information from env.php programmatically

    Basically you want to inject MagentoFrameworkAppDeploymentConfig and then use its get() method:

    /**
     * Gets data from flattened data
     *
     * @param string $key
     * @param mixed $defaultValue
     * @return mixed|null
     */
    public function get($key = null, $defaultValue = null)
    

    GitHub Source

    For example: $deploymentConfig->get('db/connection/default/host');

    Additional: env.php reference

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search