I installed the package:
composer require vlucas/phpdotenv
and in the root of my project i have a .env
file with some configuration variable.
Now i try to use PHP dotenv to get the ENV variable availables to the prod and dev environments.
So, to do this, i’ve modified the yii
file inside of environments/dev
and environments/prod
folders in order to get env variables available inside the project.
So the yii
file is :
#!/usr/bin/env php
<?php
/**
* Yii console bootstrap file.
*/
defined('YII_DEBUG') or define('YII_DEBUG', true);
defined('YII_ENV') or define('YII_ENV', 'dev');
require __DIR__ . '/vendor/autoload.php';
require __DIR__ . '/vendor/yiisoft/yii2/Yii.php';
require __DIR__ . '/common/config/bootstrap.php';
require __DIR__ . '/console/config/bootstrap.php';
$dotenv = DotenvDotenv::createImmutable(__DIR__ . '/');
$dotenv->load();
$config = yiihelpersArrayHelper::merge(
require __DIR__ . '/common/config/main.php',
require __DIR__ . '/common/config/main-local.php',
require __DIR__ . '/console/config/main.php',
require __DIR__ . '/console/config/main-local.php'
);
$application = new yiiconsoleApplication($config);
$exitCode = $application->run();
exit($exitCode);
For example i modified my main-local.php
inside environmentscommon
folder
'db' => [
'class' => yiidbConnection::class,
'dsn' => 'mysql:host=localhost;dbname='.$_ENV['DB_NAME'],
'username' => $_ENV['DB_USER'],
'password' => $_ENV['DB_PASSWORD'],
'charset' => 'utf8',
'enableSchemaCache' => $_ENV['DB_USE_CACHE'],
'schemaCacheDuration' => 3600,
'schemaCache' => 'cache',
],
But when i run php init
$_ENV variable is empty. Is this the correct way to set .env file? what am I doing wrong?
This is my .env
file
# APPLICATION CONFIG
APP_NAME="Yii -CMS"
APP_LANGUAGE=it
APP_CHARSET=utf-8
APP_ENV=dev # [dev | test | prod]
APP_DEBUG=true # use 'false' in production
# DATABASE CONFIG
DB_HOST=localhost
DB_CONNECTION=mysql
DB_PORT=3306
DB_USER=root
DB_PASSWORD=''
DB_NAME=yiicms
DB_USE_CACHE=false # use 'true' in production