Skip to content

Commit d4394d0

Browse files
authored
Add support for BOM-signed env files (#501)
1 parent 7261bb0 commit d4394d0

File tree

3 files changed

+26
-4
lines changed

3 files changed

+26
-4
lines changed

src/Util/Str.php

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -41,11 +41,19 @@ public static function utf8(string $input, string $encoding = null)
4141
\sprintf('Illegal character encoding [%s] specified.', $encoding)
4242
);
4343
}
44-
44+
$converted = $encoding === null ?
45+
@\mb_convert_encoding($input, 'UTF-8') :
46+
@\mb_convert_encoding($input, 'UTF-8', $encoding);
47+
/**
48+
* this is for support UTF-8 with BOM encoding
49+
* @see https://en.wikipedia.org/wiki/Byte_order_mark
50+
* @see https://github.com/vlucas/phpdotenv/issues/500
51+
*/
52+
if (\substr($converted, 0, 3) == "\xEF\xBB\xBF") {
53+
$converted = \substr($converted, 3);
54+
}
4555
/** @var \GrahamCampbell\ResultType\Result<string,string> */
46-
return Success::create(
47-
$encoding === null ? @\mb_convert_encoding($input, 'UTF-8') : @\mb_convert_encoding($input, 'UTF-8', $encoding)
48-
);
56+
return Success::create($converted);
4957
}
5058

5159
/**

tests/Dotenv/Store/StoreTest.php

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -127,4 +127,15 @@ public function testFileReadMultipleWithoutShortCircuitMode()
127127
$builder->make()->read()
128128
);
129129
}
130+
public function testFileReadWithUtf8WithBomEncoding()
131+
{
132+
self::assertSame(
133+
[
134+
self::$folder.\DIRECTORY_SEPARATOR.'utf8-with-bom-encoding.env' => "FOO=bar\nBAR=baz\nSPACED=\"with spaces\"\n",
135+
],
136+
Reader::read(
137+
Paths::filePaths([self::$folder], ['utf8-with-bom-encoding.env'])
138+
)
139+
);
140+
}
130141
}
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
FOO=bar
2+
BAR=baz
3+
SPACED="with spaces"

0 commit comments

Comments
 (0)