Skip to content

Instantly share code, notes, and snippets.

@devlifeX
Created October 9, 2020 03:57
Show Gist options
  • Save devlifeX/c669cb7c134735e12702e0e42f3019ff to your computer and use it in GitHub Desktop.
Save devlifeX/c669cb7c134735e12702e0e42f3019ff to your computer and use it in GitHub Desktop.
PHP ENV file handler, just include it and put .env file in your code, use like this: $_ENV['foot']; in your code.
<?php
class DotENV
{
private $options = [];
public function __construct($options)
{
$this->options = $options;
if (!$this->dotEnvOptionsHandler()) {
return;
}
$this->init();
}
public function init()
{
if ($this->dotEnvExist()) {
$values = $this->dotEnvValues();
return $values;
}
return [];
}
public function dotEnvOptionsHandler()
{
$requireFields = ['dir', 'file'];
foreach ($requireFields as $key => $field) {
if (!isset($this->options[$field]) || empty($this->options[$field])) {
error_log("DotEnv: $field is Empty, DotEnv Exit!");
return false;
}
}
$path = $this->options['dir'].DIRECTORY_SEPARATOR . $this->options['file'];
$this->options['path'] = $path;
return true;
}
public function dotEnvExist()
{
return @file_exists($this->options['path']);
}
public function dotEnvValues()
{
try {
$output = [];
$envContent = file_get_contents($this->options['path']);
$envArray = explode(PHP_EOL, $envContent);
foreach ($envArray as $key => $env) {
$val = explode('=', $env);
$output[$val[0]] =$val[1];
}
return $output;
} catch (\Throwable $th) {
return [];
}
}
}
$dotEnv = new DotENV(['dir' => __DIR__, 'file' => '.env']);
$_ENV = $dotEnv->init();
@lrjohnst
Copy link

lrjohnst commented Nov 9, 2021

I've built in a simple check if the .env line actually contains the '=' symbol. This way, I won't get warnings for each of the '#' comments that I put in my .env. To replicate: replace lines 56-67 with:

if(str_contains($env, "=")) { $val = explode('=', $env); $output[$val[0]] = $val[1]; }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment