Library that adds the ability to access variables from '.env', $_ENV, and $_SERVER using the getenv() function
composer require fkrzski/dotenv
Add your application configuration variables to .env
file in your project. Next add .env
to .gitignore
file! You should create a .env.example
file to have a skeleton with variable names for your contributors
APP_NAME="My App Name" # My app name
API_KEY=YourApiKey # My api key
use Dotenv\Dotenv;
$dotenv = new Dotenv('.env');
$dotenv->start();
$dotenv = new Dotenv('path/to/file/myenvfile.env');
// Now you are using myenvfile.env from /path/to/file folder
$dotenv = new Dotenv('path/to/file/myenvfile.env', 'path/to/file/mysecondenvfile.env');
echo getenv('APP_NAME');
echo $_SERVER['APP_NAME'];
echo $_ENV['APP_NAME'];
// output: My App Name
.env
file
APP_NAME="App Name"
API_KEY=ApiKey
APP_NAME="Second App Name"
API_KEY=SecondApiKey
PHP file
$dotenv->start(['APP_NAME']);
echo getenv('APP_NAME');
echo getenv('API_KEY');
// Output:
// Second App Name
// ApiKey
Second possibility
.env
file
APP_NAME="App Name"
API_KEY=ApiKey
APP_NAME="Second App Name"
API_KEY=SecondApiKey
PHP file
$dotenv->start(['*']);
echo getenv('APP_NAME');
echo getenv('API_KEY');
// Output:
// Second App Name
// SecondApiKey
.env
file
APP_NAME="App Name"
PHONE_NUMBER=111222333
PHP file
$dotenv->start();
$dotenv->validator()->validate([
'APP_NAME' => 'required|alnum',
'PHONE_NUMBER' => 'required|integer',
]);
/* All validating rules:
* - required
* - letters (Letters and spaces only)
* - alnum (Letters, numers and spaces)
* - integer
* - boolean (true/false)
* - float
*/
Dotenv::single('VAR', 'value');
echo getenv("VAR");