julienlinard/php-dotenv 问题修复 & 功能扩展

解决BUG、新增功能、兼容多环境部署,快速响应你的开发需求

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

julienlinard/php-dotenv

Composer 安装命令:

composer require julienlinard/php-dotenv

包简介

Une librairie PHP simple et moderne pour charger les variables d'environnement depuis un fichier .env

README 文档

README

🇫🇷 Read in French | 🇬🇧 Read in English

💝 Support the project

If this bundle is useful to you, consider becoming a sponsor to support the development and maintenance of this open source project.

A simple and modern PHP library for loading environment variables from a .env file.

🚀 Installation

composer require julienlinard/php-dotenv

Requirements: PHP 8.0 or higher

⚡ Quick Start

<?php

require_once __DIR__ . '/vendor/autoload.php';

use JulienLinard\Dotenv\Dotenv;

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

// Access variables
echo $_ENV['DB_HOST'];
echo $_ENV['DB_NAME'];

📋 Features

  • .env file loading
  • ✅ Comment support (lines starting with #)
  • ✅ Support for single and double quoted values
  • ✅ Multi-line value support
  • ✅ Variable expansion (${VAR} or $VAR)
  • ✅ Immutable mode (does not replace existing variables)
  • ✅ Required variable validation
  • ✅ Boolean and null value support

📖 Usage

Basic Loading

use JulienLinard\Dotenv\Dotenv;

// Create an immutable instance (does not replace existing variables)
$dotenv = Dotenv::createImmutable(__DIR__);
$dotenv->load();

Mutable Loading

// Create a mutable instance (replaces existing variables)
$dotenv = Dotenv::createMutable(__DIR__);
$dotenv->load();

Required Variable Validation

use JulienLinard\Dotenv\Dotenv;

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

// Validate that certain variables exist
$dotenv->required(['DB_HOST', 'DB_NAME', 'DB_USER', 'DB_PASS']);

Validation with Default Values

// Validate with default values
$dotenv->required(['DB_PORT'])->notEmpty()->defaultTo('3306');

Direct Variable Retrieval

// Get a variable with default value
$dbHost = Dotenv::get('DB_HOST', 'localhost');

📝 .env File Format

# Comment
DB_HOST=localhost
DB_NAME=mydatabase
DB_USER=root
DB_PASS=password123

# Quoted values
APP_NAME="My Application"
APP_URL='https://example.com'

# Boolean values
DEBUG=true
MAINTENANCE=false

# Null value
CACHE_DRIVER=null

# Variable expansion
APP_URL=https://example.com
API_URL=${APP_URL}/api

# Multi-line values (with quotes)
DESCRIPTION="This is a description
on multiple lines"

🔒 Security

  • Variables are loaded into $_ENV and $_SERVER
  • Immutable mode by default (does not replace existing system variables)
  • Variable name validation (alphanumeric characters and underscores only)

🔗 Integration with Other Packages

Integration with core-php

core-php automatically includes php-dotenv. Use loadEnv() to load variables.

<?php

use JulienLinard\Core\Application;

$app = Application::create(__DIR__);

// Load the .env file
$app->loadEnv();

// Variables are now available in $_ENV
$dbHost = $_ENV['DB_HOST'];
$dbName = $_ENV['DB_NAME'];

Standalone Usage

php-dotenv can be used independently of all other packages.

<?php

require_once __DIR__ . '/vendor/autoload.php';

use JulienLinard\Dotenv\Dotenv;

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

// Access variables
echo $_ENV['DB_HOST'];
echo $_ENV['DB_NAME'];

Usage with Other Frameworks

<?php

// Laravel, Symfony, or any PHP framework
use JulienLinard\Dotenv\Dotenv;

Dotenv::createImmutable(__DIR__)->load();

// Variables are now available
$config = [
    'database' => [
        'host' => $_ENV['DB_HOST'],
        'name' => $_ENV['DB_NAME'],
        'user' => $_ENV['DB_USER'],
        'password' => $_ENV['DB_PASS']
    ]
];

📚 API Reference

Dotenv::createImmutable(string $path, string $file = '.env'): Dotenv

Creates an immutable instance that does not replace existing variables.

$dotenv = Dotenv::createImmutable(__DIR__);
$dotenv = Dotenv::createImmutable(__DIR__, '.env.local');

Dotenv::createMutable(string $path, string $file = '.env'): Dotenv

Creates a mutable instance that replaces existing variables.

$dotenv = Dotenv::createMutable(__DIR__);

load(): void

Loads the .env file and sets environment variables in $_ENV and $_SERVER.

$dotenv->load();

required(array $variables): Validator

Validates that the specified variables exist. Throws an exception if a variable is missing.

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

get(string $key, mixed $default = null): mixed

Retrieves a variable with an optional default value.

$dbHost = Dotenv::get('DB_HOST', 'localhost');
$dbPort = Dotenv::get('DB_PORT', 3306);

💡 Advanced Usage Examples

Validation with Default Values

use JulienLinard\Dotenv\Dotenv;

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

// Validate with default value
$dotenv->required(['DB_PORT'])->notEmpty()->defaultTo('3306');

Conditional Loading

// Load .env.local if available, otherwise .env
$envFile = file_exists(__DIR__ . '/.env.local') ? '.env.local' : '.env';
$dotenv = Dotenv::createImmutable(__DIR__, $envFile);
$dotenv->load();

Usage in a CLI Script

#!/usr/bin/env php
<?php

require_once __DIR__ . '/vendor/autoload.php';

use JulienLinard\Dotenv\Dotenv;

// Load environment variables
Dotenv::createImmutable(__DIR__)->load();

// Use variables
echo "Database connection: " . $_ENV['DB_HOST'] . "\n";

🧪 Tests

composer test

📝 License

MIT License - See the LICENSE file for more details.

🤝 Contributing

Contributions are welcome! Feel free to open an issue or a pull request.

💝 Support the project

If this bundle is useful to you, consider becoming a sponsor to support the development and maintenance of this open source project.

Developed with ❤️ by Julien Linard

julienlinard/php-dotenv 适用场景与选型建议

julienlinard/php-dotenv 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 191 次下载、GitHub Stars 达 13, 最近一次更新时间为 2025 年 11 月 16 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「configuration」 「environment」 「env」 「dotenv」 「variables」 「php8」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 julienlinard/php-dotenv 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 julienlinard/php-dotenv 我们能提供哪些服务?
定制开发 / 二次开发

基于 julienlinard/php-dotenv 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 191
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 14
  • 点击次数: 21
  • 依赖项目数: 1
  • 推荐数: 0

GitHub 信息

  • Stars: 13
  • Watchers: 0
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2025-11-16