Loads environment variables from .env file to getenv(), $_ENV and $_SERVER.
Now we create a file named .env
APP_ENV=dev
DATABASE_DNS=mysql:host=localhost;dbname=test;
DATABASE_USER=root
DATABASE_PASSWORD=root
Let's create the class that will parse .env file.
<?php
namespace DevCoder;
class DotEnv
{
/**
* The directory where the .env file can be located.
*
* @var string
*/
protected $path;
public function __construct(string $path)
{
if(!file_exists($path)) {
throw new \InvalidArgumentException(sprintf('%s does not exist', $path));
}
$this->path = $path;
}
public function load() :void
{
if (!is_readable($this->path)) {
throw new \RuntimeException(sprintf('%s file is not readable', $this->path));
}
$lines = file($this->path, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
foreach ($lines as $line) {
if (strpos(trim($line), '#') === 0) {
continue;
}
list($name, $value) = explode('=', $line, 2);
$name = trim($name);
$value = trim($value);
if (!array_key_exists($name, $_SERVER) && !array_key_exists($name, $_ENV)) {
putenv(sprintf('%s=%s', $name, $value));
$_ENV[$name] = $value;
$_SERVER[$name] = $value;
}
}
}
}
How to use ?
<?php
use DevCoder\DotEnv;
(new DotEnv(__DIR__ . '/.env'))->load();
echo getenv('APP_ENV');
// dev
echo getenv('DATABASE_DNS')
// mysql:host=localhost;dbname=test;
Ideal for small project
Simple and easy!
https://github.com/devcoder-xyz/php-dotenv
Top comments (6)
At most of time, I usually use the vlucas/phpdotenv package to help me to manipulate
DotEnv
file happily.And thanks for your another approach to develop a simple yet
php-dotenv
project :).Thank you so much, man. This is exactly what I needed. 🎉
Where do we put this class file, and how do we require it into the application?
you use composer ? or without composer ?
Ideally both ways? Sometimes I can, some projects I can't.
easy , if you use composer , create this class in your project and use it automaticly .
If you not use composer, create this class without namespace and include file class