To configure environment variables in Symfony, follow these steps:
Create a .env
file in the root directory of your Symfony project. This file will contain all your environment variables.
Define your environment variables in the .env
file using the key-value pair format. For example:
DB_HOST=localhost
DB_PORT=3306
DB_NAME=my_database
In your Symfony configuration files (e.g., config/services.yaml
, config/packages/framework.yaml
), you can access the environment variables using the %env(VARIABLE_NAME)%
syntax. For example:
parameters:
database_host: '%env(DB_HOST)%'
database_port: '%env(DB_PORT)%'
database_name: '%env(DB_NAME)%'
Make sure to add the .env
file to your .gitignore
file to prevent sensitive information from being exposed in your version control system.
You can also create additional .env
files for different environments (e.g., .env.prod
, .env.dev
) and specify which one to use by setting the APP_ENV
environment variable in your web server configuration.
When deploying your Symfony project, make sure to set the environment variables on the server where the project will run. You can do this by creating a .env.local
file on the server or by setting the environment variables directly in your web server configuration.
By following these steps, you can configure environment variables in Symfony and securely manage sensitive information in your project.