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 class NameParser {
Parsing a full name into components in PHP
string-parsing
arrays
normalization
Intermediate
8 steps
typescript
import { Module } from '@nestjs/common'; import { ConfigModule } from '@nestjs/config'; import * as Joi from 'joi';
Validating env config at boot in NestJS
configuration
schema-validation
environment-variables
Intermediate
8 steps
php
<?php namespace App\Services\Checkout;
Validating coupons with Laravel's Pipeline
pipeline
chain of responsibility
transactions
Intermediate
7 steps
ruby
class UserAgentParser BROWSERS = [ [/Edg\/([\d.]+)/, "Edge"], [/OPR\/([\d.]+)/, "Opera"],
Parsing user-agent strings in Ruby
regex
pattern-matching
lookup-tables
Intermediate
8 steps
javascript
function evaluate(expression) { const tokens = tokenize(expression); let pos = 0;
Building a recursive descent calculator
parsing
recursion
operator-precedence
Intermediate
8 steps
php
<?php namespace App\Services;
How a password strength validator works in PHP
validation
regular-expressions
data-driven
Intermediate
8 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.