Skip to content

Unable to create environement variables that starts with an underscore ( _ ) #52630

@nicDamours

Description

@nicDamours

Symfony version(s) affected

6.3.7 ( Dotenv component )

Description

I've been trying to setup a symfony project and it requires me to have a .env file that contains variable that starts with an underscore. For example:

_APP_ID=123

However, when I'm trying to parse this file, to use the variable in my code, I'm having the follow error message.

Uncaught Symfony\Component\Dotenv\Exception\FormatException: Invalid character in variable name in "/path/to/my/project/.env"

This is unexpected since it looks like POSIX variable should be able to start with an underscore.

How to reproduce

  1. Create a new symfony project
  2. In this project, update the .env file to add the following variable
_TEST_VARIABLE=result
  1. Create a route that will retrieve the variable's value using the getenv function
  2. Start the project
  3. In your browser, call the previously created route
  4. In your serve console, notice the error.

Possible Solution

I've done some digging around and it looks like all we need is to allow the underscore character, in the first characters set of the VARNAME_REGEX of the Dotenv class.

I will create a PR that fixes the problem.

Additional Context

Here is a screenshot of the console with the error
image

And here is the complete .env file. There is no other .env file overriding it.

# In all environments, the following files are loaded if they exist,
# the latter taking precedence over the former:
#
#  * .env                contains default values for the environment variables needed by the app
#  * .env.local          uncommitted file with local overrides
#  * .env.$APP_ENV       committed environment-specific defaults
#  * .env.$APP_ENV.local uncommitted environment-specific overrides
#
# Real environment variables win over .env files.
#
# DO NOT DEFINE PRODUCTION SECRETS IN THIS FILE NOR IN ANY OTHER COMMITTED FILES.
# https://symfony.com/doc/current/configuration/secrets.html
#
# Run "composer dump-env prod" to compile .env files for production use (requires symfony/flex >=1.2).
# https://symfony.com/doc/current/best_practices.html#use-environment-variables-for-infrastructure-configuration

###> symfony/framework-bundle ###
APP_ENV=dev
APP_SECRET=secret
###< symfony/framework-bundle ###

# The variable that causes problem
_TEST_ENV_1=default

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions