Loads environment variables from
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
PHP dotenv is a PHP version of the original Ruby dotenv. InstallationInstallation is super-easy via Composer: $ composer require vlucas/phpdotenv or add it by hand to your UpgradingWe follow semantic versioning, which means breaking changes may occur between major releases. We have upgrading guides available for V2 to V3, V3 to V4 and V4 to V5 available here. UsageThe Add your application configuration to a S3_BUCKET="dotenv" SECRET_KEY="souper_seekret_key" Now create a file named S3_BUCKET="devbucket" SECRET_KEY="abc123" You can then load $dotenv = Dotenv\Dotenv::createImmutable(__DIR__); $dotenv->load(); To suppress the exception that is thrown when there is no $dotenv = Dotenv\Dotenv::createImmutable(__DIR__); $dotenv->safeLoad(); Optionally you can pass in a filename as the second parameter, if you would like to use
something other than $dotenv = Dotenv\Dotenv::createImmutable(__DIR__, 'myconfig'); $dotenv->load(); All of the defined variables are now available in the $s3_bucket = $_ENV['S3_BUCKET']; $s3_bucket = $_SERVER['S3_BUCKET']; Putenv and GetenvUsing $s3_bucket = getenv('S3_BUCKET'); $s3_bucket = $_ENV['S3_BUCKET']; $s3_bucket = $_SERVER['S3_BUCKET']; Nesting VariablesIt'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 BASE_DIR="/var/webroot/project-root" CACHE_DIR="${BASE_DIR}/cache" TMP_DIR="${BASE_DIR}/tmp" Immutability and Repository CustomizationImmutability refers to if Dotenv is allowed to overwrite existing environment variables. If you want Dotenv to overwrite existing environment variables, use $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 relevant if one is calling the "create" method using the $repository = Dotenv\Repository\RepositoryBuilder::createWithNoAdapters() ->addAdapter(Dotenv\Repository\Adapter\EnvConstAdapter::class) ->addWriter(Dotenv\Repository\Adapter\PutenvAdapter::class) ->immutable() ->make(); $dotenv = Dotenv\Dotenv::create($repository, __DIR__); $dotenv->load(); The above example will write loaded values to By means of another example, one can also specify a set of variables to be allow listed. That is, only the variables in the allow list will be loaded: $repository = Dotenv\Repository\RepositoryBuilder::createWithDefaultAdapters() ->allowList(['FOO', 'BAR']) ->make(); $dotenv = Dotenv\Dotenv::create($repository, __DIR__); $dotenv->load(); Requiring Variables to be SetPHP 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'); 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
Empty VariablesBeyond 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:
Integer VariablesYou 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 may only want to enforce validation rules when a variable is set. We support this too: $dotenv->ifPresent('FOO')->isInteger(); Boolean VariablesYou may need to ensure a variable is in the form of a boolean, accepting "true", "false", "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:
Similarly, one may write:
$dotenv->ifPresent('FOO')->isBoolean(); Allowed ValuesIt 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:
It is also possible to define a regex that your environment variable should be. $dotenv->required('FOO')->allowedRegexValues('([[:lower:]]{3})'); CommentsYou can comment your # this is a comment VAR="value" # comment VAR=value # comment Parsing Without LoadingSometimes you just wanna parse the file and resolve the nested environment variables, by giving us a string, and have an array returned back to you. While this is already possible, it is a little fiddly, so we have provided a direct way to do this: // ['FOO' => 'Bar', 'BAZ' => 'Hello Bar'] Dotenv\Dotenv::parse("FOO=Bar\nBAZ=\"Hello \${FOO}\""); This is exactly the same as: Dotenv\Dotenv::createArrayBacked(__DIR__)->load(); only, instead of providing the directory to find the file, you have directly provided the file contents. Usage NotesWhen
a new developer clones your codebase, they will have an additional one-time step to manually copy the SecurityIf you discover a security vulnerability within this package, please send an email to . All security vulnerabilities will be promptly addressed. You may view our full security policy here. LicensePHP dotenv is licensed under The BSD 3-Clause License. For EnterpriseAvailable as part of the Tidelift Subscription The maintainers of What is env file in PHP?env file is a plain text file which contains environment variables definitions which are designed so your PHP application will parse them, bypassing the Apache, NGINX and PHP-FPM. The usage of . env files is popular in many PHP frameworks such as Laravel which has built-in support for parsing .
How can I get environment variable in PHP?Using getenv()
In addition to using PHP's Superglobals, you can also use getenv() to retrieve an environment variable. If the function is called without an argument, then it returns all available environment variables. If an argument is passed, however, the value of an environment variable with that name is returned.
What is the use of env variables?An environment variable is a dynamic "object" on a computer, containing an editable value, which may be used by one or more software programs in Windows. Environment variables help programs know what directory to install files in, where to store temporary files, and where to find user profile settings.
What is in env variable?An environment variable is a variable whose value is set outside the program, typically through functionality built into the operating system or microservice. An environment variable is made up of a name/value pair, and any number may be created and available for reference at a point in time.
|