DEV Community

Cover image for PHP - Create your own dotenv to loads environment variables from .env file
F.R Michel
F.R Michel

Posted on

PHP - Create your own dotenv to loads environment variables from .env file

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
Enter fullscreen mode Exit fullscreen mode

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;
            }
        }
    }
}


Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

Ideal for small project
Simple and easy!
https://github.com/devcoder-xyz/php-dotenv

Top comments (6)

Collapse
 
peter279k profile image
peter279k

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 :).

Collapse
 
pratik149 profile image
Pratik Rane

Thank you so much, man. This is exactly what I needed. 🎉

Collapse
 
benhickson profile image
Ben Hickson

Where do we put this class file, and how do we require it into the application?

Collapse
 
fadymr profile image
F.R Michel

you use composer ? or without composer ?

Collapse
 
benhickson profile image
Ben Hickson

Ideally both ways? Sometimes I can, some projects I can't.

Thread Thread
 
fadymr profile image
F.R Michel

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