dotenv requires .env file on production

Also looked into this, my current solution is to use Lumen's way (as of 6 June 2016) which was suggested in a discussion:

try {
    (new Dotenv\Dotenv(__DIR__.'/../'))->load();
} catch (Dotenv\Exception\InvalidPathException $e) {
    //
}

You can still do some additional exception handling if needed (e.g. fall to default values or do some validation.


If you have problem to create an APP_ENV variable, this code is easier :

$dotenv = new Dotenv\Dotenv(__DIR__);
if(file_exists(".env")) {
    $dotenv->load();
}

Dotenv was built around an idea, that it will be used in development environments only. Thus, it always expects .env file to be present.

The solution you didn't like is a recommended way to use Dotenv. And it seems, that it won't change in near future. Related discussion in project's issue tracker: https://github.com/vlucas/phpdotenv/issues/63#issuecomment-74561880

Note, that Mark offers there a good approach for production/staging environments, which skips file loading, but not validation

$dotenv = new Dotenv\Dotenv();
if(getenv('APP_ENV') === 'development') {
    $dotenv->load(__DIR__);
}
$dotenv->required('OTHER_VAR');