From bb4fef2bf035a50170fd95e5b146152834126008 Mon Sep 17 00:00:00 2001 From: Christian Flothmann Date: Mon, 16 Sep 2024 09:16:29 +0200 Subject: [PATCH] throw a meaningful exception when parsing dotenv files with BOM --- Dotenv.php | 8 +++++++- Tests/DotenvTest.php | 10 ++++++++++ Tests/fixtures/file_with_bom | 1 + 3 files changed, 18 insertions(+), 1 deletion(-) create mode 100644 Tests/fixtures/file_with_bom diff --git a/Dotenv.php b/Dotenv.php index b454452..d164aa0 100644 --- a/Dotenv.php +++ b/Dotenv.php @@ -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); } } } diff --git a/Tests/DotenvTest.php b/Tests/DotenvTest.php index 644126d..8ba0230 100644 --- a/Tests/DotenvTest.php +++ b/Tests/DotenvTest.php @@ -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'); + } } diff --git a/Tests/fixtures/file_with_bom b/Tests/fixtures/file_with_bom new file mode 100644 index 0000000..242249b --- /dev/null +++ b/Tests/fixtures/file_with_bom @@ -0,0 +1 @@ +FOO=BAR