Accessing ENV vars from PHP

How to read values from environment variables in PHP.

# 1. use the getenv function
echo getenv("MY_ENV_VAR");

# 2. use the global
echo $_SERVER["MY_ENV_VAR"];
php
  1. The getenv() PHP function accepts a key and returns it's value.
  2. Use the global variable $_SERVER.

Frameworks and content management systems will parse and use ENV vars automatically. Usually .env files are supported for local development. A config file to grab may $dbHost = env('DB_HOST');.

  • Laravel: Use the env() helper function
  • Craft CMS: getenv() in config/general.php
  • WordPress: getenv() to access environment variables in wp-config.php

Found a tpyo?Edit