X

How to parse a .env file with PHP

Parsing a .env (dotenv) file in PHP can be done by using a dedicated library or writing a simple custom parser. The .env file is typically used to store configuration variables in a key-value pair format, which can be easily read into the application environment.

Using a Library (like vlucas/phpdotenv)

One of the most popular libraries for this purpose is vlucas/phpdotenv. It's widely used in many PHP projects, including Laravel.

Install the phpdotenv Library

You can install it via Composer:

composer require vlucas/phpdotenv

Load .env File

In your PHP code, use the library to load the .env file:

<?php

require_once 'vendor/autoload.php';

$dotenv = Dotenv\Dotenv::createImmutable(__DIR__);
$dotenv->load();

// Now you can access the variables using getenv()
$var = getenv('YOUR_ENV_VARIABLE');
echo $var;

?>

Replace 'YOUR_ENV_VARIABLE' with the actual name of your environment variable.

Writing a Custom .enf File Parser

If you prefer not to use an external library, you can write a basic parser:

<?php

$envPath = __DIR__ . '/.env';
$env = file($envPath, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);

foreach ($env as $line) {
if (strpos(trim($line), '#') === 0) {
continue; // Skip comments
}
list($name, $value) = explode('=', $line, 2);
$name = trim($name);
$value = trim($value);

// Optionally remove surrounding quotes
$value = trim($value, "\"'");

// Set the environment variable
putenv("$name=$value");
}

// Usage
$var = getenv('YOUR_ENV_VARIABLE');
echo $var;

?>

This script reads the .env file, skips comments, and sets each variable using the putenv() function. You can then access these variables using getenv().

Notes

  • Security: Be cautious with environment variables, especially when dealing with sensitive data.
  • File Path: Ensure that the path to the .env file is correct.
  • Variable Names: The environment variable names should not contain spaces.
  • Quotation Marks: If your values are enclosed in quotes, the custom parser example includes code to remove them.

Convert .env File into a Array in PHP

Below is a PHP function that parses a .env file into an associative array. The function takes the path to the .env file as a parameter and returns an array where each key-value pair corresponds to an environment variable defined in the .env file.

function parseEnvFile($filePath) {
  if (!file_exists($filePath)) {
    // Optionally handle the case where the file does not exist
    throw new Exception("The file at $filePath does not exist.");
  }

  $envArray = [];
  $lines = file($filePath, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);

  foreach ($lines as $line) {
    if (strpos(trim($line), '#') === 0) {
    continue; // Skip comments
  }

  list($name, $value) = explode('=', $line, 2);
  $name = trim($name);
  $value = trim($value);

  // Remove surrounding quotes from the value
  $value = trim($value, "\"'");

  $envArray[$name] = $value;
 }

  return $envArray;
}

Example usage:

$envFilePath = 'path/to/your/.env'; // Replace with the actual path to your .env file
$envVars = parseEnvFile($envFilePath);
print_r($envVars); // Print the resulting array

This function works as follows:

  • It first checks if the file exists and throws an exception if it does not.
  • It reads the file line by line, ignoring empty lines and lines starting with # (which are considered comments).
  • Each line is split into a name and a value at the = character.
  • Leading and trailing whitespace is trimmed from both the name and the value.
  • The function also removes any surrounding quotes from the values.
  • It then adds these as key-value pairs to the $envArray.

This function is useful for simple .env parsing needs. However, for more complex scenarios, especially those involving variable interpolation or special parsing rules, you might still want to consider using a dedicated library like vlucas/phpdotenv.

Till Brehm:
X

Headline

You can control the ways in which we improve and personalize your experience. Please choose whether you wish to allow the following:

Privacy Settings