An open API service indexing awesome lists of open source software.

https://github.com/markhadjar/dotenv

Loads environment variables to $_ENV from .env file.
https://github.com/markhadjar/dotenv

dotenv env environment

Last synced: 2 months ago
JSON representation

Loads environment variables to $_ENV from .env file.

Awesome Lists containing this project

README

          

# Dotenv

Loads environment variables to `$_ENV` from `.env` file.

## Why Dotenv?

An application typically deploys to multiple environments, each requiring different configuration. Storing credentials directly in the codebase puts sensitive data into version control and makes switching between environments error-prone.

Dotenv loads configuration from a `.env` file into `$_ENV` at runtime. Because each environment uses its own `.env` with the appropriate values, the code does not need to change and credentials stay out of version control. This provides a portable way to manage environment variables across different runtimes without needing to modify server-level configuration files.

## Requirements

PHP 8.4+

## Installation

Install via Composer:

```bash
composer require markhadjar/dotenv
```

## Usage

The `.env` file is generally kept out of version control since it can contain sensitive values such as API keys and passwords.

Create a `.env` file in your project root and add it to your `.gitignore` to keep it out of version control:

```shell
S3_BUCKET=your-bucket-name
SECRET_KEY=your-secret-key
```

Create a `.env.example` file and commit this to version control. The purpose is to let developers know what variables are required without exposing the real values. Variables should be left blank or set to dummy data:

```shell
S3_BUCKET=dev-bucket
SECRET_KEY=P@ssword1
```

Load the environment variables in your application:

```php
$dotenv = new \MarkHadjar\Dotenv\Dotenv(__DIR__);
$dotenv->load();
```

Access your configuration values via `$_ENV`:

```php
$s3Bucket = $_ENV['S3_BUCKET'];
$secretKey = $_ENV['SECRET_KEY'];
```

**Note:** Variables already present in `$_ENV` will not be overwritten by the `.env` file. If the `.env` file is not found or cannot be read, an exception will be thrown.