CodeBlanks Logo Icon CodeBlanks

Environment management

PHP course · Expert · Lesson 47/54

Learn to manage environment variables with a .env file and getenv().

Environment variables

Environment variables separate configuration from code: database passwords, API keys and debug flags do not get baked into the source.

In PHP you read a single variable with getenv('APP_ENV'); the $_ENV superglobal holds them all. putenv('KEY=value') defines a new one.

A .env file holds KEY=VALUE lines; you can load it as an array with parse_ini_file.

Parsing the .env file

parse_ini_file('.env') reads the file and returns an associative array like ['APP_ENV' => 'production', 'DEBUG' => '0']. Lines starting with # count as comments.

To push values into $_ENV you assign $_ENV[$key] = $val; then you read from the superglobal directly instead of getenv.

In production the .env file is never committed; it is placed on the server during deploy. An accidental commit leaks secrets.

Exercise Generate and parse .env

Generate a .env file with PHP: write APP_ENV=production and DEBUG=0 lines via file_put_contents. Then read it back with parse_ini_file and print each key/value pair as KEY=value.

Show example solution
First write the file with file_put_contents(".env", "APP_ENV=production\nDEBUG=0\n");. Then read with $env = parse_ini_file(".env");. Print with foreach ($env as $key => $val) { echo $key . "=" . $val . "\n"; }.
Example solution:
<?php
// Generate and parse .env
file_put_contents(".env", "APP_ENV=production\nDEBUG=0\n");
$env = parse_ini_file(".env");
foreach ($env as $key => $val) {
    echo $key . "=" . $val . "\n";
}

Test yourself

  1. Complete the getenv call

    <?php
    $env = ____('APP_ENV');
    print_r(["env" => $env]);
    
    Show answer
    <?php
    $env = getenv('APP_ENV');
    print_r(["env" => $env]);
    
  2. Match the environment tools

    getenv
    Reads one variable
    $_ENV
    Superglobal array
    parse_ini_file
    Reads a file
    putenv
    Defines a variable
  3. Which function loads a .env file as an array?

    • file_get_contents
    • parse_ini_file
    • fopen
    • require
    Show answer

    parse_ini_file — Correct. parse_ini_file turns the .env file into a KEY => VALUE array.

All lessons in Expert