In this post I will show you a way to create your own .env solution for PHP to store and retrieve environment variables.
First I take no credit for the implementation, I just had to build off of the base implementation for my own personal situation. You can get the project from this link below.
https://dev.to/fadymr/php-create-your-own-php-dotenv-3k2i
My issue with using this “out of the box” is that I had some keys to store that needed to keep the newline char in the variable. To fix this, I created my own function.
Code
<?php
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);
$currentVal = "";
$currentName = "";
$stillProcessingLine = 0;
for($i = 0; $i < sizeof($lines); $i++){
if($stillProcessingLine){
$currentVal .= "\n".$lines[$i];
}
if(strpos($lines[$i], '*') === 0){
$stillProcessingLine = 0;
$arr = explode('=', $lines[$i], 2);
$currentName = $arr[0];
$currentVal = $arr[1];
$currentName = str_replace("*", "", $currentName);
}
if($i < sizeof($lines)-1){
if(strpos($lines[$i+1], "*") === false){
$stillProcessingLine = 1;
}else {
$stillProcessingLine = 0;
}
} else {
$stillProcessingLine = 0;
}
if($stillProcessingLine === 0){
$name = trim($currentName);
$value = trim($currentVal);
if (!array_key_exists($name, $_SERVER) && !array_key_exists($name, $_ENV)) {
putenv(sprintf('%s=%s', $name, $value));
$_ENV[$name] = $value;
$_SERVER[$name] = $value;
}
}
}
}
}
?>
Create a sample .env file
*DB_HOST=localhost
*DB_NAME=databaseName
*DB_USER=admin
*DB_PASS=password
*SECRET_KEY=sampleKey
*test_pubk=-----sample-line-----
sample-line
sample-line
-----sample-line-----
*test_pk=-----sample-line-----
sample-line
sample-line
sample-line
sample-line
sample-line
sample-line
sample-line
sample-line
-----sample-line-----
To use, add these two lines to the documents you load this in
require_once("DotEnv.php");
(new DotEnv(__DIR__ . '/.env'))->load();
Now you can call one of your environment variables using
$_ENV['DB_HOST']
This helped my because I didn’t necessarily want to add composer to my test environment due to the limitation on my production environment.