fkrzski / dotenv
Library that adds the ability to access variables from '.env', $_ENV, and $_SERVER using the getenv() function
V1.1.0
2022-01-31 13:12 UTC
Requires
- php: >=7.0
Requires (Dev)
- phpunit/phpunit: 9.*
This package is auto-updated.
Last update: 2025-06-29 01:52:37 UTC
README
Library that adds the ability to access variables from '.env', $_ENV, and $_SERVER using the getenv() function
Installation
composer require fkrzski/dotenv
Usage
Basics
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
Include Dotenv
class
use Dotenv\Dotenv;
Load .env
variables
$dotenv = new Dotenv('.env'); $dotenv->start();
Custom path or file name
$dotenv = new Dotenv('path/to/file/myenvfile.env'); // Now you are using myenvfile.env from /path/to/file folder
Many .env
files
$dotenv = new Dotenv('path/to/file/myenvfile.env', 'path/to/file/mysecondenvfile.env');
Retrieving variables values
echo getenv('APP_NAME'); echo $_SERVER['APP_NAME']; echo $_ENV['APP_NAME']; // output: My App Name
Overwrtitting a variable
.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
Validating and requiring variables
.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 */
Put single variable
Dotenv::single('VAR', 'value'); echo getenv("VAR");