We are moving our forum in GitHub Discussions. For questions about Phalcon v3/v4 you can visit here and for Phalcon v5 here.

Update config.php with environment variable

Hi All,

How can we use environment variable in config.php. i'm looking for a solution to change DB host,password, port config value on based on environment. like its different for development and staging.

return new \Phalcon\Config([
    'db' => [
        'host' => get_env('DB_HOST'),
    ],
]);

Create an ENV define in you init file and add an env [dev,preprod,prod] index in your config.php Then you'll can use

$this->config[ENV]->database->host
...
return new \Phalcon\Config([
  'db' => [
      'host' => get_env('DB_HOST'),
  ],
]);

Hi,

I have tried out below but its not working for me.

return new \Phalcon\Config(array( 'database' => array( 'adapter' => 'Mysql', 'host' => get_env('SQL_HOST')

Sorry, i made a typo.

The correct method is getenv, without underscore!

return new \Phalcon\Config([
    'db' => [
        'host' => getenv('DB_HOST'),
    ],
]);
return new \Phalcon\Config([
 'db' => [
     'host' => get_env('DB_HOST'),
 ],
]);

Hi,

I have tried out below but its not working for me.

return new \Phalcon\Config(array( 'database' => array( 'adapter' => 'Mysql', 'host' => get_env('SQL_HOST')



8.3k

There are two typical attitudes:

  1. Local file with parameters (it's called ".env" or similar)
  2. Local variable with defined env (env is defined in .htaccess, server, system etc.):
    $env = getenv('APPLICATION_ENV');

and config files for each env, which expand/overwrite base config: config.yml -- config_dev.yml -- config.prod.yml

It's better to follow with standards and config is static in nature, so variables, functions, control structures etc are not welcomed.

Thanks but don't want to store prod configuration information in repo.

There are two typical attitudes:

  1. Local file with parameters (it's called ".env" or similar)
  2. Local variable with defined env (env is defined in .htaccess, server, system etc.):
    $env = getenv('APPLICATION_ENV');

and config files for each env, which expand/overwrite base config: config.yml -- config_dev.yml -- config.prod.yml

It's better to follow with standards and config is static in nature, so variables, functions, control structures etc are not welcomed.



67
edited Dec '20

Hi,

I had exactly the same problem.

What worked for me is to add this line just after the ServerName directive of my vhost config file something like :

setEnv MY_ENV_VAR_NAME_IN_APACHE_AS_I_WANT_IN_MY_CODE ${MY_ENV_VAR_NAME_IN_MY_SYSTEM}

The code in Phalcon is correct, in your case you should just add in your apache conf (should be kind of similar with nginx I think):

setEnv DB_HOST ${DB_HOST}

From what I understood, this is because apache is serving his own env vars (for his process), which are different of the OS/System env vars.

Hope this will help someone.