DEV Community

Indian Modassir
Indian Modassir

Posted on

PHP Dotenv Loads environment variables

Banner

Loads environment variables from .env to getenv(), $_ENV and $_SERVER automatically.

Installation

Installation is super-easy via Composer

composer require lazervel/dotenv
Enter fullscreen mode Exit fullscreen mode

or add it by hand to your composer.json file.

Usage

use Dotenv\Dotenv;
require 'vendor/autoload.php';
Enter fullscreen mode Exit fullscreen mode

If already .env file existing on current directory

$dotenv = Dotenv::process(__DIR__);
$dotenv->load();
Enter fullscreen mode Exit fullscreen mode

If already .env file existing on current directory without throwing error

$dotenv = Dotenv::process(__DIR__);
$dotenv->safeLoad();
Enter fullscreen mode Exit fullscreen mode

If already .env file existing on current directory

$dotenv = Dotenv::process(__DIR__, 'myconfig.env');
$dotenv->load();
Enter fullscreen mode Exit fullscreen mode

Loads multiple .env files.

$dotenv = Dotenv::process(__DIR__, ['.env.local', '.env.example', '.env'], false);
$dotenv->load();
Enter fullscreen mode Exit fullscreen mode

All of the defined variables are now available in the $_ENV and $_SERVER super-globals.

$s3_bucket = $_ENV['S3_BUCKET'];
$s3_bucket = $_SERVER['S3_BUCKET'];
Enter fullscreen mode Exit fullscreen mode

Nesting Variables

It's possible to nest an environment variable within another, useful to cut down on repetition.

This is done by wrapping an existing environment variable in ${…} e.g.

BASE_DIR="/var/webroot/project-root"
CACHE_DIR="${BASE_DIR}/cache"
TMP_DIR="${BASE_DIR}/tmp"
Enter fullscreen mode Exit fullscreen mode

Requiring Variables to be Set

PHP dotenv has built in validation functionality, including for enforcing the presence of an environment variable. This is particularly useful to let people know any explicit required variables that your app will not work without.

You can use a single string:

$dotenv->required('DATABASE_DSN');
Enter fullscreen mode Exit fullscreen mode

Or an array of strings:

$dotenv->required(['DB_HOST', 'DB_NAME', 'DB_USER', 'DB_PASS']);
Enter fullscreen mode Exit fullscreen mode

Security

If you discover a security vulnerability within this package, All security vulnerabilities will be promptly addressed. You may view our full security policy here.

License

PHP dotenv is licensed under MIT License.

Top comments (18)

Collapse
 
ravavyr profile image
Ravavyr

This is what frustrates me...
You do not need composer for this AT ALL.

A simple load_dotenv function can load your env file vars into your global [or whatever object you want to use since you're not supposed to use globals too much even though they exist for this exact purpose]

Stop using composer to install an entire library of code you don't know when you can just write 10 lines of code that do the same, or close enough, considering you can make it do exactly what you need, no more, no less. Zero dependencies.

function load_dotenv($path = '.env') {
    global $env;
    $env = [];
    if (!file_exists($path)) return;
    $lines = file($path, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
    foreach ($lines as $line) {
        if (strpos(trim($line), '#') === 0) continue;
        list($key, $value) = array_pad(explode('=', trim($line), 2), 2, '');
        $env[trim($key)] = trim($value, " \t\n\r\0\x0B\"'");
    }
}

// Example usage in application
load_dotenv(); // Load .env file

// Access $env globally in other parts of the application
global $env;
echo $env['DB_HOST']; // Outputs value of DB_HOST from .env

// Or use in a function
function get_db_config() {
    global $env;
    return [
        'host' => $env['DB_HOST'] ?? 'localhost',
        'user' => $env['DB_USER'] ?? 'root',
        'pass' => $env['DB_PASS'] ?? ''
    ];
}```

Enter fullscreen mode Exit fullscreen mode
Collapse
 
xwero profile image
david duymelinck

.env libraries exist for years now. phpdotenv is the oldest but there is also Symfony dotenv.

Next to loading .env files phpdotenv also can validate values. Which can be a help during the deploy process.

I only use it when I need to deploy on shared servers.
If the server is a virtualised container I add my keys and values to the environment variables, and use $_ENV.

Collapse
 
indianmodassir profile image
Indian Modassir

Yes, you're right. The validation feature of phpdotenv is quite useful during deployment, especially when there's no option to set environment variables directly. In containers, I also mostly rely on system-level environment variables. It's the best practice to maintain a clean environment in production.

Collapse
 
ravavyr profile image
Ravavyr

My point was more the dependency on all these libraries instead of devs learning to write small functions that get the job done just the same thereby reducing their dependencies [and conflicts that arise] plus making their codebases that much smaller.

Again, it's about being dependent on external code and the problems that arise from that.

Thread Thread
 
indianmodassir profile image
Indian Modassir

Your are right bro, but most of developers used external library like lazy developers

Thread Thread
 
xwero profile image
david duymelinck • Edited

While I agree that keeping your codebase as small as possible is a good thing. Building on the knowledge of other people makes you work faster.
In a time where we as developers are supposed to create solutions in hours instead of days depending on third party knowledge will be the default. But what people forget is that always has bin that way. Look they did it, it can't be hard if they did it.

Dependencies are not inherently bad. You just have to pick the right dependencies.
If you are going to add dependencies without evaluation that is a bad thing. But it says more about the person that added it than about the library itself.

Like I don't trust this library for some reasons I put in another comment. But after reading the comment where the author thinks most developers are lazy in a bad way, I trust this library even less.
Libraries are build because people think they can make life easier for others. That is why I like the open source spirit in the PHP community.

Sure you can make a fork of a library, but if it has no added value why would i want to use the fork instead of the library that contains years of knowledge.

From this comment you see choosing a dependency is not a do or don't thing. It depends, pun intended.

Thread Thread
 
ravavyr profile image
Ravavyr

"You just have to pick the right dependencies."
And how many devs do you know who actually do that?

How many know how to determine if they can trust a library or not?

How many are clairvoyant and able to tell that the next update will cause conflicts between some of their dependencies?

I agree, it depends, and choosing less is always safer in the long term for any client projects. Pet projects, meh, no one's gonna use it but you, have at it.

Thread Thread
 
indianmodassir profile image
Indian Modassir

Absolutely valid points β€” thanks for sharing your perspective!
You're right, evaluating whether a dependency is trustworthy isn't something every developer thinks about early on, and even experienced devs can get bitten by unexpected updates or conflicts.

For this library, I’ve made an effort to keep dependencies minimal and transparent, exactly to avoid those long-term issues you mentioned. I also agree β€” for client work, less is usually safer. Pet projects are a great place to experiment, but production needs caution.

Appreciate your input β€” it adds an important angle to the conversation!

Thread Thread
 
xwero profile image
david duymelinck

And how many devs do you know who actually do that?

I assume any developer that takes pride in the job.

How many know how to determine if they can trust a library or not?

There are a few simple rules I use:

  • what is the popularity?
  • what is the maintenance record?
  • who is the author?
  • have the tests value
  • are there strange things in the code at first glance

if you know the problem space you can check out the code, and see if it differs with the solution you had in mind.

How many are clairvoyant and able to tell that the next update will cause conflicts between some of their dependencies?

You don't need to be clairvoyant. If dependencies have dependencies of their own, they should work as expected until there is a major version update of a dependency.
The reason semantic version numbers exist is to lock in a version until it is needed to update.
If a developer updates dependencies without thinking about the consequences, that is not a dependency problem.

Collapse
 
indianmodassir profile image
Indian Modassir

But this method not be loads multiple .env files and not working nested variable like ${APP_NAME} and not working proper Error Handling

Collapse
 
ravavyr profile image
Ravavyr

You're talking about exceptions. Most apps only use one .env file, and why should you have multiple anyway?
Doesn't it make sense to have your creds in one secured file?

And yea i pulled that method out of my chatGPT in like 5 seconds, of course it's not perfect.
You're missing the point.

Thread Thread
 
indianmodassir profile image
Indian Modassir

"I get your point, but many real-world applications do use multiple .env files – especially when managing dev, staging, and production environments separately. That's exactly why I added that support in my library. It's not just about 'creds in one file', it's about maintainability and separation of concerns.

Collapse
 
xwero profile image
david duymelinck

What bothers me the most, is that I see things that just are ripped off from phpdotenv.

  • the logo
  • the repository about

This makes me highly suspicions about the code.

Also having 20 contributors on a repository that started 10 months ago, seems a bit much.

Collapse
 
anik_sikder_313 profile image
Anik Sikder

Environment variables are the unsung heroes of clean, secure deployments, and this package makes it ridiculously easy to manage them.
As a full-stack dev working with Django, FastAPI, and React, I love seeing PHP tools embrace workflows with features like nested variables, multi-file loading, and required checks. It’s like bringing the best of 12-factor app principles into every stack.
I often tell junior devs in my Bangla-speaking community: কনফিগারেঢন কো঑ে না, ΰ¦ͺরিবেঢে ΰ¦°ΰ¦Ύΰ¦–ΰ§‹, এঀে অ্যাΰ¦ͺ আরও নিরাΰ¦ͺদ আর ΰ¦Έΰ¦Ήΰ¦œΰ§‡ ΰ¦šΰ¦Ύΰ¦²ΰ¦Ύΰ¦¨ΰ§‹ যায়ΰ₯€ (Keep configuration in the environment, not in the code, it makes your app safer and easier to run.)

Collapse
 
indianmodassir profile image
Indian Modassir

Absolutely agree β€” environment variables play a crucial role in clean and secure deployments. Great to see the PHP ecosystem adopting features like nested variables, multi-file loading, and required checks. This really brings the 12-factor app principles into play. Also, love how you're sharing this mindset with your Bangla-speaking community β€” that line is spot on!

Collapse
 
parag_nandy_roy profile image
Parag Nandy Roy

life-saver for messy configs..

Collapse
 
mexikode profile image
MexiKode βš™

the trend to over complicate simple things continues xD

Collapse
 
indianmodassir profile image
Indian Modassir

Haha true xD sometimes what looks simple outside needs a bit of extra wiring inside πŸ˜… But I totally get your pointβ€”I'll keep an eye on making things as simple as possible πŸš€

Some comments may only be visible to logged-in visitors. Sign in to view all comments.