Description
Symfony version(s) affected
7.1.3
Description
Hi!
I was working on a project that had a .env file.
But I faced an error that said:
PHP Fatal error: Uncaught Symfony\Component\Dotenv\Exception\FormatException: Invalid character in variable name in "~/project-path/.env" at line 1. ...FOO=bar\nBAR=baz\nS... ^ line 1 offset 0 in /tmp/symfony/src/Symfony/Component/Dotenv/Dotenv.php:553
After some debugging time, I realized the file encoding caused the problem!
The encoding of the .env file is UTF8 BOM
I attached the sample file that has this problem (I changed the extension of the file to txt, because GitHub does not allow upload it):
utf8-with-bom-encoding.txt
How to reproduce
First of all, install symfony/dotenv
using composer:
mkdir /tmp/test-symfony-dotenv
cd /tmp/test-symfony-dotenv
composer require symfony/dotenv
Then, create a simple PHP file named test.php
inside /tmp/test-symfony-dotenv
, Then put this simple peace of PHP code inside it:
<?php
require_once "./vendor/autoload.php";
use Symfony\Component\Dotenv\Dotenv;
$dotenv = new Dotenv();
$dotenv->load(__DIR__.'/utf8-with-bom-encoding.txt');
Then, download this file and put it inside your /tmp/test-symfony-dotenv
directory:
utf8-with-bom-encoding.txt
Then, simply run:
php /tmp/test-symfony-dotenv/test.php
You got this error:
➜ test-symfony-dotenv php /tmp/test-symfony-dotenv/test.php
PHP Fatal error: Uncaught Symfony\Component\Dotenv\Exception\FormatException: Invalid character in variable name in "/tmp/test-symfony-dotenv/utf8-with-bom-encoding.txt" at line 1.
...FOO=bar\nBAR=baz\nS...
^ line 1 offset 0 in /tmp/test-symfony-dotenv/vendor/symfony/dotenv/Dotenv.php:547
Stack trace:
#0 /tmp/test-symfony-dotenv/vendor/symfony/dotenv/Dotenv.php(272): Symfony\Component\Dotenv\Dotenv->createFormatException()
#1 /tmp/test-symfony-dotenv/vendor/symfony/dotenv/Dotenv.php(245): Symfony\Component\Dotenv\Dotenv->lexVarname()
#2 /tmp/test-symfony-dotenv/vendor/symfony/dotenv/Dotenv.php(557): Symfony\Component\Dotenv\Dotenv->parse()
#3 /tmp/test-symfony-dotenv/vendor/symfony/dotenv/Dotenv.php(81): Symfony\Component\Dotenv\Dotenv->doLoad()
#4 /tmp/test-symfony-dotenv/test.php(8): Symfony\Component\Dotenv\Dotenv->load()
#5 {main}
thrown in /tmp/test-symfony-dotenv/vendor/symfony/dotenv/Dotenv.php on line 547
Possible Solution
I suggest to check if the data of a env file starts with BOM signature, we remove it and the try to parse it
symfony/src/Symfony/Component/Dotenv/Dotenv.php
Lines 229 to 232 in b19a108
And change it to this:
public function parse(string $data, string $path = '.env'): array
{
if (\substr($data, 0, 3) == "\xEF\xBB\xBF") {
$data = \substr($data, 3);
}
$this->data = str_replace(["\r\n", "\r"], "\n", $data);
$this->path = $path;
Additional Context
Sample BOM-signed file:
utf8-with-bom-encoding.txt