How to create and use environment variable .env yii2

Viewed 11415

I want to create a file .env:

 FACEBOOK_CLIENT_ID=*****
 FACEBOOK_CLIENT_SECRET=*****

and use variable for config

'facebook' => [
                'class' => 'yii\authclient\clients\Facebook',
                'clientId' => env('FACEBOOK_CLIENT_ID'),
                'clientSecret' => env('FACEBOOK_CLIENT_SECRET'),
            ],
4 Answers

There's a package for Yii2 you can use for dotenv

https://github.com/yiithings/yii2-dotenv

Install:

composer require --prefer-dist yiithings/yii2-dotenv "*"

Usage:

Create a .env in project root directory

DB_HOST="localhost"
DB_NAME="yii2basic"
DB_USER="root"
DB_PASS="YourPassword"

config/db.php

return [
    'class' => 'yii\db\Connection',
    'dsn' => 'mysql:host='. env('DB_HOST') .';dbname='. env('DB_NAME'),
    'username' => env('DB_USER'),
    'password' => env('DB_PASS'),
    'charset' => 'utf8',
];

You could use the dotenv package offered by Symfony. https://symfony.com/doc/current/components/dotenv.html

using it in a PHP file.

use Symfony\Component\Dotenv\Dotenv;

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

// You can also load several files
$dotenv->load(__DIR__.'/.env', __DIR__.'/.env.dev');

.env file

DB_USER=root
DB_PASS=pass

accessing the variables from the .env file

$dbUser = $_ENV['DB_USER'];
// you can also use ``$_SERVER``
Related