Environmental
Variables
https://github.com/sketchings/example-env
What are Environments?
Software Environments
● Local
● Dev
● QA
● Staging
● Production
What are environmental variables?
● Tied to the environment
○ Not tied to a language
○ Not tied to an application
● Used for things that change based on the environment
How can you set them up?
● Apache/Nginx (System wide or Virtual Hosts)
● Hosting Company Dashboard
● Docker
● .htaccess
● Composer Package (.env)
Docker Environment:
DB_SERVER: "db"
DB_NAME: "env-test"
DB_USERNAME: "env"
DB_PASSWORD: "password"
CONFIG_ENV: "development"
S3_BUCKET: "docker bucket"
Using a Package
PHP dotenv
Loads environment variables from .env to getenv(), $_ENV
and $_SERVER automagically.
https://github.com/vlucas/phpdotenv
.env File
DB_SERVER="db"
DB_NAME="env-test"
DB_USERNAME="env"
DB_PASSWORD="password"
CONFIG_ENV="development"
S3_BUCKET="dotenv bucket"
<?php
require __DIR__ . '/vendor/autoload.php';
// can be a relative or absolute path
// optional second parameter for filename, default is .env
$dotenv = DotenvDotenv::createImmutable(__DIR__);
if (getenv('CONFIG_ENV') != "production") {
$dotenv->load();
}
//Immutability refers to if Dotenv is allowed to
overwrite existing environment variables. If you want
Dotenv to overwrite existing environment variables,
use createMutable instead of createImmutable:
$dotenv = DotenvDotenv::createMutable(__DIR__);
Mutability
<?php
require __DIR__ . '/vendor/autoload.php';
$dotenv = DotenvDotenv::createImmutable(__DIR__);
if (getenv('CONFIG_ENV') != "production") {
$dotenv->load();
}
$dotenv->required(
['DB_SERVER', 'DB_NAME', 'DB_USERNAME', 'DB_PASSWORD']
);
What about Security?
● Never check .env files into source control
○ Same applies to sensitive configuration
● Use a secrets manager
○ https://www.phparch.com/magazine/2019/06/how-to-tame-your-data/
Alena Holligan
● Lead Software Engineer at Lumen Learning
● PHPDX User Group Leader
● Web Developer for 20 years
● Twitter @alenaholligan
File: https://github.com/sketchings/example-env
Slide and to rate this Talk: https://joind.in/talk/cf3cc

Environmental variables