phpdotenv

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

What is phpdotenv?

phpdotenv is a popular PHP library for managing application configuration through environment variables. It allows loading settings from a .env file into the $_ENV array and global getenv() variables, which simplifies separating configuration from code. It was created based on the Ruby dotenv library and is widely used in modern PHP frameworks (Laravel, Symfony).

Why is phpdotenv needed?

When developing applications, it is often necessary to store sensitive data (database passwords, API keys) separately from the code. phpdotenv solves this problem: you create a .env file that is not included in the repository (added to .gitignore), and the library loads it into the environment. This ensures security, flexibility (different settings for dev/staging/prod), and compliance with the 12-factor app principle.

Installing phpdotenv

Install the library via Composer:

composer require vlucas/phpdotenv

Make sure you have Composer and PHP version 7.1 or higher installed.

Main Features

  • Loading .env file — parsing key=value with support for comments (#) and empty lines.
  • Required variables — checking for the presence of necessary keys using required().
  • Typing — automatic conversion of strings to types (boolean, integer, null).
  • Security — escaping special characters, support for quotes.
  • Immutability — protection against overwriting existing environment variables.

PHP Code Example

require 'vendor/autoload.php';

use Dotenv\\Dotenv;

// Load .env from the root directory$dotenv = Dotenv::createImmutable(__DIR__);$dotenv->load();

// Now variables are accessible via getenv()$dbHost = getenv('DB_HOST');$dbName = getenv('DB_NAME');

// Or via $_ENVecho $_ENV['APP_ENV']; // 'local'

// Check required variables$dotenv->required(['DB_HOST', 'DB_NAME']);

// Example .env file:// DB_HOST=localhost// DB_NAME=test// APP_ENV=local

When to Use phpdotenv

The library is ideal for:

  • PHP web applications (Laravel, Symfony, Slim).
  • CLI scripts and microservices.
  • Projects where quick configuration changes are needed without modifying code.
  • Team development — each developer can have their own .env.
  • CI/CD pipelines — variables are set via the server environment, not through a file.

Important: Never commit the .env file to the repository. Create a .env.example with a template for colleagues.

Recommendations