Load a .env file with PHP
Developers often hit a wall when transitioning from simple scripts to projects requiring environment-specific configuration. The immediate instinct is to reach for vlucas/phpdotenv, a robust Composer package that parses .env files and populates the $_ENV or getenv() superglobals. However, the error message shown in the screenshotâError: Call to undefined function Dotenv\Dotenv\createImmutable()âis a classic symptom of how PHP resolves namespaces at runtime, not necessarily a flaw in the library itself.
The root cause is almost always an execution order issue. You cannot load the environment variables after you attempt to use them within the same request lifecycle if the autoload mechanism hasn't yet registered the Dotenv class. In your index.php, the script likely attempts to define routes or include other files (like bdd.php) before it ever reaches the line $dotenv->load(). By the time bdd.php executes, the namespace for Dotenv might not be available in the current context, or the file was included before the composer autoloader fully initialized the specific class you are trying to call.
The Correct Initialization Order
To resolve this, you must ensure the environment loader is invoked as early as possible in the request lifecycle, ideally before any logic that depends on those variables runs. This is often handled by a dedicated bootstrap file rather than scattering it across index.php.
Create a file named bootstrap.php in your project root:
<?php
// 1. Load Composer's autoloader first (if using Composer)
require __DIR__ . '/vendor/autoload.php';
// 2. Then load the environment variables
$dotenv = Dotenv\Dotenv::createImmutable(__DIR__);
$dotenv->load();
Update your index.php to include this file at the very top:
<?php
require __DIR__ . '/bootstrap.php';
// Now you can safely use getenv() or $_ENV in bdd.php
function DBConnect() {
$user = getenv('DB_USER');
$pass = $_ENV['DB_PASSWORD'];
// Proceed with connection logic...
}
Why createImmutable is Recommended
The Dotenv::createImmutable(__DIR__) method is the modern standard for new projects. It creates a configuration object that loads variables from a single file without checking for an existing .env file or attempting to write back to it (which requires write permissions on the directory). This makes it safer for shared hosting environments where you cannot modify the .env file directly, and it prevents accidental data leaks if a .env.local file exists in a public web root.
Debugging Namespace Resolution
If the error persists even after reordering your includes, inspect the actual stack trace. The message Call to undefined function Dotenv\Dotenv\createImmutable specifically indicates that PHP is looking for the global function createImmutable, but it cannot find it within the Dotenv namespace because the autoloader hasn't mapped Dotenv classes yet.
This usually happens if:
- You are calling
$dotenv->load()beforevendor/autoload.phpis required. - You have an older version of the package that uses a different class name (e.g.,
create()vscreateImmutable()). Check yourcomposer.jsonto ensure you are usingvlucas/phpdotenv:^5.6or higher, ascreateImmutablewas introduced in later versions to align with the new API.
Trade-offs and Security Considerations
While loading environment variables into memory is convenient for accessing them via getenv() or $_ENV, be aware that this exposes the values to all subsequent PHP code in the request. If you are building a modular application, consider using a dedicated configuration manager class (like Laravel's config system) rather than relying on global superglobals. This keeps your code decoupled and allows you to cache the configuration at the start of the request if performance becomes a bottleneck.
For legacy scripts or simple tools, vlucas/phpdotenv remains one of the most reliable solutions because it handles parsing logic that regex-based manual implementations often get wrong, such as handling comments, escaped values, and multiline strings correctly.
If you are moving away from vanilla PHP toward an MVC architecture like Laravel, the framework abstracts this complexity entirely into its service container, but understanding these initialization steps is crucial for maintaining legacy projects or building lightweight frameworks of your own.
