Setting up and working with DotEnv - PHP Environment Variables

Posted one year ago

Get started by installing composer.

Then providing how you’ve installed it (with an alias or not you will need to run one of two commands)


php composer.phar require vlucas/phpdotenv

or 

composer require vlucas/phpdotenv

This should install the necessary files and folders.

Depending on where you want to save your vendor folder may change the location of the following lines, however I like to keep mine above public_html.


$loc = dirname($_SERVER['DOCUMENT_ROOT']); // Declare a var directing the user to one folder above the servering directory (public_html / html)
require($loc . "/vendor/autoload.php"); // Require the vendor autoload so we can use DotEnv

$dotenv = new Dotenv\Dotenv($loc); // Let DotEnv know where to look for the .env file
$dotenv->load(); // instantiate dotenv


Then create a file one location about public_html “.env

We can then create name valued pairs within the .env file.


  FOO="BAR"

Now within any file we call the above dotenv class, we have the variables available to us as a $_ENV array var.


  echo $_ENV['FOO']; // Returns BAR

NOTE: Variables are case sensitive and you should never commit your .env file to a version control, it’s also good practice to ignore the vendor file too.