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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Refusing to overwrite pre-existing environment variables lets real system config take precedence over the file.
- 2Splitting on the first delimiter with a limit keeps values containing that delimiter intact.
- 3Quoted values need their own normalization rules distinct from bare, comment-trailed values.
Related explainers
php
<?php namespace App\Http\Controllers;
Streaming a filtered CSV export in Laravel
streaming
csv-export
query-builder
Intermediate
9 steps
rust
use std::cmp::Ordering; use std::str::FromStr; #[derive(Debug, Clone, PartialEq, Eq)]
Parsing and ordering semantic versions in Rust
parsing
trait-implementation
ordering
Intermediate
8 steps
php
<?php namespace App\Http\Middleware;
Idempotent requests with Laravel middleware
idempotency
middleware
caching
Advanced
8 steps
python
import os from datetime import timedelta
Class-based config in a Flask app factory
configuration
app-factory
inheritance
Intermediate
7 steps
ruby
class ApacheLogParser LINE_PATTERN = /\A(?<ip>\S+)\s\S+\s\S+\s\[(?<time>[^\]]+)\]\s"(?<method>[A-Z]+)\s(?<path>\S+)\s(?<protocol>[^"]+)"\s(?<status>\d{3})\s(?<bytes>\d+|-)/ TIME_FORMAT = "%d/%b/%Y:%H:%M:%S %z"
Parsing Apache logs with named captures
regex
named-captures
parsing
Intermediate
6 steps
php
<?php namespace App\Services;
Batch image resizing with PHP GD
image-processing
constructor-promotion
match-expression
Intermediate
10 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/writing-a-env-file-loader-in-php-explained-php-30aa/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.