Skip to content
/ Dotenv Public

Library that adds the ability to access variables from '.env', $_ENV, and $_SERVER using the getenv() function

License

Notifications You must be signed in to change notification settings

fkrzski/Dotenv

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

19 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Dotenv

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");

About

Library that adds the ability to access variables from '.env', $_ENV, and $_SERVER using the getenv() function

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published