Skip to content

Commit

Permalink
throw a meaningful exception when parsing dotenv files with BOM
Browse files Browse the repository at this point in the history
  • Loading branch information
xabbuh committed Sep 16, 2024
1 parent 974e6b8 commit bb4fef2
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 1 deletion.
8 changes: 7 additions & 1 deletion Dotenv.php
Original file line number Diff line number Diff line change
Expand Up @@ -568,7 +568,13 @@ private function doLoad(bool $overrideExistingVars, array $paths): void
throw new PathException($path);
}

$this->populate($this->parse(file_get_contents($path), $path), $overrideExistingVars);
$data = file_get_contents($path);

if ("\xEF\xBB\xBF" === substr($data, 0, 3)) {
throw new FormatException('Loading files starting with a byte-order-mark (BOM) is not supported.', new FormatExceptionContext($data, $path, 1, 0));
}

$this->populate($this->parse($data, $path), $overrideExistingVars);
}
}
}
10 changes: 10 additions & 0 deletions Tests/DotenvTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -604,4 +604,14 @@ public function testBootEnv()
$resetContext();
rmdir($tmpdir);
}

public function testExceptionWithBom()
{
$dotenv = new Dotenv();

$this->expectException(FormatException::class);
$this->expectExceptionMessage('Loading files starting with a byte-order-mark (BOM) is not supported.');

$dotenv->load(__DIR__.'/fixtures/file_with_bom');
}
}
1 change: 1 addition & 0 deletions Tests/fixtures/file_with_bom
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
FOO=BAR

0 comments on commit bb4fef2

Please sign in to comment.