How to create & use environment variables in Craft CMS
Add the variable to the .env file in capital letters and use it through the control panel or in code through App::env('ENV_VAR_NAME'), where ENV_VAR_NAME is the name of your variable.
The following tutorial walks you through how to add and use environment variables in Craft CMS.
Please note that you must restart your Craft CMS project for the environment variable to register in the Control Panel.
Step One: Add your variable
Open the .env file at the root of your project and add your environment variable.
It is recommended that you use capital letters with "_" for spaces. i.e. my environment variable becomes MY_ENVIRONMENT_VARIABLE.
Step Two: Use your variable
Environment variables can be used in the control panel or in code.
In the Control Panel
If you wish to use it in the control panel, restart your Craft CMS instance by deploying your code or stopping and starting your local environment.
To use it in code, first import the App craft helper functionality using the following line:
Then use the following snippet, replacing ENV_VAR_NAME with the environment variable name that you used in Step One.
A sample use of this code can be found in the config/app.php of our starter project.
We are actively looking for feedback on how to improve this resource. Please send us a note to firstname.lastname@example.org with any thoughts or feedback you may have.