Environment variables: Best way to save configuration variables in a PHP application

Introduction

Almost all PHP application use configuration variables to store configurations; like database credentials, memcache details, 3rd part api details and many others.

According to The Twelve-factor App all these config should Never be committed to SCM and developers should keep it separate from codebase. Further they suggest that config should be stored in environment variables (env vars or env).

Quick Tip: I suggest you to read The Twelve-factor app, which provides the Best guidelines for creating a modern SaaS application for better development practices and avoid cost of software erosion.

We at The Web Fosters always follow this guidelines for developing any application for our clients.

PHP inbuilt function for environment variable

Getting env variable: PHP supports getenv(‘name_of_environment_variable’) function and Superglobal likes $_SERVER, $_ENV which you can use to get any environment variables.

PHP supports getenv(‘name_of_environment_variable’) function and Superglobal likes $_SERVER, $_ENV which you can use to get any environment variables. Setting env variables: You can use putenv() to set environment variables.

Example: putenv(“DB_USERNAME=thewebfosters”)

Support for .env in frameworks

Most of the modern PHP frameworks supports the use of environment variable with ease. Some frameworks provides .env.example file with required environment variables present in it, you should copy this file as new .env file with variable set according to your environment.

Laravel: More details on Laravel official documentation here .

More details on Laravel official documentation here . Phalcon: Read details of setting it here

Read details of setting it here Codeigniter: More details on codeigniter offcial documentation here

Adding support for .env in custom frameworks

You maybe developing using some custom frameworks or legacy frameworks or any other framework with support for this. No worries, you can easily add the support for Environment variable in these frameworks using this package. Also you can contribute to these frameworks.

I find the use of .env file very useful, every-time I have add a new config variable or setup application in a different server.

Looking forward to hear about your experience, do share it below.

Thanks 🙂