PHP dotenv

自动将环境变量从 .env 加载到 getenv()、$_ENV 和 $_SERVER 中。「 Loads environment variables from `.env` to `getenv()`, `$_ENV` and `$_SERVER` automagically. 」

Github星跟蹤圖

PHP dotenv

自动地从 .env 加载环境变量到 getenv()、$_ENV 和 $_SERVER。

这是原始 Ruby dotenv 的PHP版本

从V2升级

版本3中的新功能是对多行变量( #301 )的一流支持,以及在我们尝试读取和修改环境的哪些部分(#300 )方面的更大灵活性。因此, 你将需要将任何出现的 new Dotenv(...) 替换为 Dotenv::create(...) ,因为我们的新原生构造函数现在采用 Loader 实例,以便在需要时可以真正对其进行自定义。最后, 应该注意的是,加载器将不再调整值(#302 )。Loader::load() 及其调用者现在返回一个与它们的值一起加载的变量的关联数组, 而不是环境文件中的原始行数组(#306 )。

有关详细信息,请参阅 发行说明升级指南

为什么 .env?

您永远不应该在代码中存储敏感凭据。在环境中存储配置十二因素应用程序的原则之一。任何可能在部署环境之间发生变化的事情 -- 例如数据库凭证或第三方服务的凭证 -- 都应该从代码中提取到环境变量中。

基本上,.env文件是一种简单的方法,可以加载应用程序所需的自定义配置变量,而无需修改 .htaccess 文件或 Apache/nginx 虚拟主机。 这意味着您无需编辑项目之外的任何文件,无论您如何运行项目,所有环境变量始终都会设置 -- Apache,Nginx,CLI,甚至 PHP 5.4 的内置 Web 服务器。 它比你知道设置环境变量的所有其他方式更容易,你会喜欢它!

  • 不编辑 Apache 或 Nginx 中的虚拟主机
  • 没有将 php_value 标志添加到 .htaccess 文件
  • EASY 可移植性和所需 ENV 值的共享
  • 与 PHP 的内置 Web 服务器和 CLI runner 兼容

使用Composer进行安装

curl -s http://getcomposer.org/installer | php
php composer.phar require vlucas/phpdotenv

或者对于已存在的项目

composer require vlucas/phpdotenv

用法

.env 文件通常不受版本控制,因为它可能包含敏感的 API 密钥和密码。 创建一个单独的 .env.example 文件,其中定义了所有必需的环境变量,敏感的除外,它们是用户为自己的开发环境提供的,或者是在别处传递给项目协作者。 然后,项目协作者将 .env.example 文件独立地复制到本地 .env,并确保所有设置对于其本地环境都是正确的,填写密钥或在必要时提供自己的值。 在此用法中,应将 .env 文件添加到项目的 .gitignore 文件中,以便协作者永远不会提交它。 此用法可确保版本控制历史记录中不会包含任何敏感密码或 API 密钥,因此安全漏洞的风险较小,并且永远不必与所有项目协作者共享生产值。

将应用程序配置添加到项目根目录中的. env 文件中。确保. env 文件已添加到您的. gitignore 中, 以便不签入代码

S3_BUCKET="dotenv"
秘密键 = "souper _ seekret _ key"

现在创建一个名为. env. 例子的文件, 并将其签入项目中。这应该具有您需要设置的 ENV 变量, 但这些值应该是空白的或用虚拟数据填充的。这样做的目的是让人们知道需要哪些变量, 但不要给他们敏感的生产价值。

S3_BUCKET="devbucket"
SECRET_KEY="abc123"

然后, 您可以在应用程序中加载. env:

$dotenv = Dotenvenv::: 创建 (_ DIR _);
$dotenv > 负载 ();

(可选) 如果您想使用. env 以外的其他参数, 也可以将文件名作为第二个参数传递

$dotenv = Dotenvenv:: 创建 (_ DIR _, "myconfig");
$dotenv > 负载 ();

现在, 所有定义的变量都可以使用 getenv 方法访问, 并且可以在 $_ ENV 和 $_ SERVER 超级全局中使用。

$s = getenv('S3_BUCKET ');
$s = _ENV['S3_BUCKET '];
$s = _SERVER['S3_BUCKET '];

您还应该能够使用框架的请求类 (如果您使用的是框架) 访问它们。

$s = $request > ');
$s = $request > ');
$s = $request 服务器 >get('S3_BUCKET ');
$s = env('S3_BUCKET ');

主要指標

概覽
名稱與所有者vlucas/phpdotenv
主編程語言PHP
編程語言PHP (語言數: 2)
平台Linux, Mac, Windows
許可證BSD 3-Clause "New" or "Revised" License
所有者活动
創建於2013-01-23 06:57:12
推送於2025-04-30 23:40:43
最后一次提交2025-05-01 00:37:27
發布數81
最新版本名稱v5.6.2 (發布於 )
第一版名稱v1.0.0 (發布於 2013-01-23 00:58:01)
用户参与
星數13.4k
關注者數173
派生數644
提交數587
已啟用問題?
問題數297
打開的問題數13
拉請求數166
打開的拉請求數0
關閉的拉請求數115
项目设置
已啟用Wiki?
已存檔?
是復刻?
已鎖定?
是鏡像?
是私有?

PHP dotenv

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

Banner

Why .env?

You should never store sensitive credentials in your code. Storing
configuration in the environment is one of
the tenets of a twelve-factor app. Anything that is
likely to change between deployment environments – such as database credentials
or credentials for 3rd party services – should be extracted from the code into
environment variables.

Basically, a .env file is an easy way to load custom configuration variables
that your application needs without having to modify .htaccess files or
Apache/nginx virtual hosts. This means you won't have to edit any files outside
the project, and all the environment variables are always set no matter how you
run your project - Apache, Nginx, CLI, and even PHP 5.4's built-in webserver.
It's WAY easier than all the other ways you know of to set environment
variables, and you're going to love it!

  • NO editing virtual hosts in Apache or Nginx
  • NO adding php_value flags to .htaccess files
  • EASY portability and sharing of required ENV values
  • COMPATIBLE with PHP's built-in web server and CLI runner

PHP dotenv is a PHP version of the original Ruby
dotenv
.

Installation with Composer

Installation is super-easy via Composer:

$ composer require vlucas/phpdotenv

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

UPGRADING FROM V3

Version 4 sees some refactoring, and support for escaping dollars in values
(https://github.com/vlucas/phpdotenv/pull/380). It is no longer possible to
change immutability on the fly, and the Loader no longer is responsible for
tracking immutability. It is now the responsibility of "repositories" to track
this. One must explicitly decide if they want (im)mutability when constructing
an instance of Dotenv\Dotenv.

For more details, please see the
release notes and
the upgrading guide.

UPGRADING FROM V2

New in Version 3 is first-class support for multiline variables
(#301) and much more
flexibility in terms of which parts of the environment we try to read and
modify (#300). Consequently,
you will need to replace any occurrences of new Dotenv(...) with
Dotenv::create(...), since our new native constructor takes a Loader
instance now, so that it can be truly customized if required. Finally, one
should note that the loader will no longer be trimming values
(#302), moreover
Loader::load() and its callers now return an associative array of the
variables loaded with their values, rather than an array of raw lines from the
environment file (#306).

For more details, please see the
release notes and
the upgrading guide.

Usage

The .env file is generally kept out of version control since it can contain
sensitive API keys and passwords. A separate .env.example file is created
with all the required environment variables defined except for the sensitive
ones, which are either user-supplied for their own development environments or
are communicated elsewhere to project collaborators. The project collaborators
then independently copy the .env.example file to a local .env and ensure
all the settings are correct for their local environment, filling in the secret
keys or providing their own values when necessary. In this usage, the .env
file should be added to the project's .gitignore file so that it will never
be committed by collaborators. This usage ensures that no sensitive passwords
or API keys will ever be in the version control history so there is less risk
of a security breach, and production values will never have to be shared with
all project collaborators.

Add your application configuration to a .env file in the root of your
project. Make sure the .env file is added to your .gitignore so it is not
checked-in the code

S3_BUCKET="dotenv"
SECRET_KEY="souper_seekret_key"

Now create a file named .env.example and check this into the project. This
should have the ENV variables you need to have set, but the values should
either be blank or filled with dummy data. The idea is to let people know what
variables are required, but not give them the sensitive production values.

S3_BUCKET="devbucket"
SECRET_KEY="abc123"

You can then load .env in your application with:

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

Optionally you can pass in a filename as the second parameter, if you would like to use something other than .env

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

All of the defined variables are now accessible with the getenv
method, and are available in the $_ENV and $_SERVER super-globals.

$s3_bucket = getenv('S3_BUCKET');
$s3_bucket = $_ENV['S3_BUCKET'];
$s3_bucket = $_SERVER['S3_BUCKET'];

You should also be able to access them using your framework's Request
class (if you are using a framework).

$s3_bucket = $request->env('S3_BUCKET');
$s3_bucket = $request->getEnv('S3_BUCKET');
$s3_bucket = $request->server->get('S3_BUCKET');
$s3_bucket = env('S3_BUCKET');

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"

Immutability and Repository Customization

Immutability refers to if Dotenv is allowed to overwrite existing environment
variables. If you want Dotenv to overwrite existing environment variables,
use createMutable instead of createImmutable:

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

Behind the scenes, this is instructing the "repository" to allow immutability
or not. By default, the repository is configured to allow overwriting existing
values by default, which is relevent if one is calling the "create" method
using the RepositoryBuilder to construct a more custom repository:

$repository = Dotenv\Repository\RepositoryBuilder::create()
    ->withReaders([
        new Dotenv\Repository\Adapter\EnvConstAdapter(),
    ])
    ->withWriters([
        new Dotenv\Repository\Adapter\EnvConstAdapter(),
        new Dotenv\Repository\Adapter\PutenvAdapter(),
    ])
    ->immutable()
    ->make();

$dotenv = Dotenv\Dotenv::create($repository, __DIR__);
$dotenv->load();

The above example will write loaded values to $_ENV and putenv, but when
interpolating environment variables, we'll only read from $_ENV. Moreover, it
will never replace any variables already set before loading the file.

Requiring Variables to be Set

Using Dotenv, you can require specific ENV vars to be defined ($_ENV, $_SERVER or getenv()) - throws an exception otherwise.
Note: It does not check for existence of a variable in a '.env' file. 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');

Or an array of strings:

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

If any ENV vars are missing, Dotenv will throw a RuntimeException like this:

One or more environment variables failed assertions: DATABASE_DSN is missing

Empty Variables

Beyond simply requiring a variable to be set, you might also need to ensure the
variable is not empty:

$dotenv->required('DATABASE_DSN')->notEmpty();

If the environment variable is empty, you'd get an Exception:

One or more environment variables failed assertions: DATABASE_DSN is empty

Integer Variables

You might also need to ensure that the variable is of an integer value. You may do the following:

$dotenv->required('FOO')->isInteger();

If the environment variable is not an integer, you'd get an Exception:

One or more environment variables failed assertions: FOO is not an integer

Boolean Variables

You may need to ensure a variable is in the form of a boolean, accepting "On", "1", "Yes", "Off", "0" and "No". You may do the following:

$dotenv->required('FOO')->isBoolean();

If the environment variable is not a boolean, you'd get an Exception:

One or more environment variables failed assertions: FOO is not a boolean

Allowed Values

It is also possible to define a set of values that your environment variable
should be. This is especially useful in situations where only a handful of
options or drivers are actually supported by your code:

$dotenv->required('SESSION_STORE')->allowedValues(['Filesystem', 'Memcached']);

If the environment variable wasn't in this list of allowed values, you'd get a
similar Exception:

One or more environment variables failed assertions: SESSION_STORE is not an
allowed value

It is also possible to define a regex that your environment variable should be.

$dotenv->required('FOO')->allowedRegexValues('({3})');

Comments

You can comment your .env file using the # character. E.g.

# this is a comment
VAR="value" # comment
VAR=value # comment

Usage Notes

When a new developer clones your codebase, they will have an additional
one-time step to manually copy the .env.example file to .env and fill-in
their own values (or get any sensitive values from a project co-worker).

Security

If you discover a security vulnerability within this package, please send an email to Graham Campbell at graham@alt-three.com. All security vulnerabilities will be promptly addressed. You may view our full security policy here.

License

PHP dotenv is licensed under The BSD 3-Clause License.