PHP code example of laxity7 / dotenv

1. Go to this page and download the library: Download laxity7/dotenv library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

laxity7 / dotenv example snippets


$dotenv = new Laxity7\Dotenv\Dotenv();
$dotenv->load(__DIR__ . '/.env');
// By default, existing variables will not be overwritten. Use the second parameter in load ()
$dotenv->load(__DIR__ . '/.env.local', true); // Optional. Variables from this file will not overwrite existing variables.

// in .env FOO=456
$dotenv = new \Laxity7\Dotenv\Dotenv();
$dotenv->load($_SERVER['DOCUMENT_ROOT'] . '/.env');

$bar = $dotenv->get('BAR', 999); // $bar = 999
$foo = $dotenv->get('FOO', 123); // $foo = 456
$foo = $_ENV['FOO']; // also 456

function env(string $name, $default = null) {
    static $env = null;

    if ($env === null) {
        $env = new \Laxity7\Dotenv\Dotenv();
        $env->load(__DIR__ . '/.env');
    }

    return $env->get($name, $default);
}

$dotenv = new \Laxity7\Dotenv\Dotenv();
$dotenv->load(__DIR__ . '/.env');
\Laxity7\Dotenv\Env::load($dotenv);
// now you can use the get method anywhere
$foo = Env::get('FOO', 'default');

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

function env(string $name, $default = null) {
    return Env::get($name, $default);
}

$foo = $_ENV['FOO']; // $foo === true
$bar = $dotenv->get('BAR'); // $bar === false
$baz = $dotenv->get('BAZ'); // $baz === 'false'