php 60 lines · 9 steps

Writing a .env file loader in PHP

A self-contained class that parses a .env file line by line and injects the values into the environment.

Explained by highlit
1<?php
2 
3namespace App\Config;
4 
5final class DotenvLoader
6{
7 public static function load(string $path): void
8 {
9 if (!is_readable($path)) {
10 throw new \RuntimeException("Env file not found or unreadable: {$path}");
11 }
12 
13 $lines = file($path, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
14 
15 foreach ($lines as $line) {
16 $line = trim($line);
17 
18 if ($line === '' || str_starts_with($line, '#')) {
19 continue;
20 }
21 
22 if (!str_contains($line, '=')) {
23 continue;
24 }
25 
26 [$name, $value] = explode('=', $line, 2);
27 $name = trim($name);
28 $value = self::normalize(trim($value));
29 
30 if (getenv($name) !== false || array_key_exists($name, $_ENV)) {
31 continue;
32 }
33 
34 putenv("{$name}={$value}");
35 $_ENV[$name] = $value;
36 $_SERVER[$name] = $value;
37 }
38 }
39 
40 private static function normalize(string $value): string
41 {
42 if ($value === '') {
43 return $value;
44 }
45 
46 $quote = $value[0];
47 
48 if (($quote === '"' || $quote === "'") && str_ends_with($value, $quote)) {
49 $value = substr($value, 1, -1);
50 
51 if ($quote === '"') {
52 $value = str_replace(['\\n', '\\"'], ["\n", '"'], $value);
53 }
54 
55 return $value;
56 }
57 
58 return preg_replace('/\s+#.*$/', '', $value) ?? $value;
59 }
60}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Refusing to overwrite pre-existing environment variables lets real system config take precedence over the file.
  2. 2Splitting on the first delimiter with a limit keeps values containing that delimiter intact.
  3. 3Quoted values need their own normalization rules distinct from bare, comment-trailed values.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Writing a .env file loader in PHP — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code