PHPackages                             mirazmac/dotenvwriter - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. mirazmac/dotenvwriter

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

mirazmac/dotenvwriter
=====================

A PHP library to write values to .env (DotEnv) files

0.7(2mo ago)19129.3k—3.2%66MITPHPPHP &gt;=7.0

Since Oct 12Pushed 2mo ago2 watchersCompare

[ Source](https://github.com/MirazMac/DotEnvWriter)[ Packagist](https://packagist.org/packages/mirazmac/dotenvwriter)[ Docs](https://mirazmac.com)[ RSS](/packages/mirazmac-dotenvwriter/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (7)Dependencies (4)Versions (8)Used By (6)

DotEnvWriter
============

[](#dotenvwriter)

A PHP library to write values to .env (DotEnv) files

Installation
------------

[](#installation)

DotEnvWriter can be installed with [Composer](https://getcomposer.org/).

```
composer require mirazmac/dotenvwriter
```

Usage
-----

[](#usage)

```
$writer = new \MirazMac\DotEnv\Writer(__DIR__ . '/' . '.env');

$writer
->set('APP_NAME', 'My App')
->set('APP_URL', 'https://laravel.com')
->set('APP_DIR', '${BASE_DIR}/app')
// Third parameter set to TRUE to force quote a single word value
->set('APP_BUCKET', 's3-bucket', true);

// Write the values to file
$writer->write();
```

API
---

[](#api)

Methods
-------

[](#methods)

### `__construct(?string $sourceFile = null)`

[](#__constructstring-sourcefile--null)

Constructs a new instance.

**Arguments**

string|null `$sourceFile` The environment file path to load values from, optional.

### ` set(string $key, string $value, bool $forceQuote = false) : self`

[](#-setstring-key-string-value-bool-forcequote--false--self)

Set the value of an environment variable, updated if exists, added if doesn't. The values must be passed as string, even if you are setting values like `TRUE` `FALSE`. This method is chainable.

**Arguments**

string `$key` The key

string `$value` The value

bool `$forceQuote` By default the whether the value is wrapped in double quotes is determined automatically. However, you may wish to force quote a value.

### ` delete(string $key) : self`

[](#-deletestring-key--self)

Delete an environment variable if present. This method is chainable.

**Arguments**

string `$key` The key

### ` rename(string $oldKey, string $newKey) : self`

[](#-renamestring-oldkey-string-newkey--self)

Rename an environment variable key in place, preserving its value and position in the file. This method is chainable.

Throws `\InvalidArgumentException` if either key name is invalid, if the old key does not exist, or if the new key already exists.

**Arguments**

string `$oldKey` The current key name

string `$newKey` The new key name

### `hasChanged() : bool`

[](#haschanged--bool)

States if one or more values has changed

### `getContent() : string`

[](#getcontent--string)

Returns the current content

### `write(bool $force = false, ?string $destFile = null) : bool`

[](#writebool-force--false-string-destfile--null--bool)

Write the contents to the `.env` file.

**Arguments**

bool `$force` By default we only write when something has changed, but you can force to write the file by setting this to TRUE.

string|null `$destFile` Destionation file. By default it's the same as `$sourceFile` is provided

F.A.Q
-----

[](#faq)

### What can this do?

[](#what-can-this-do)

`DotEnvWriter` is a PHP library that can write (add, update, delete) values to `.env` files.

### And how is this done?

[](#and-how-is-this-done)

Well.. I'm glad you asked.. it uses some bleeding edge AI algorithm.. just kidding, RegEx.. it uses RegEx to replace the values with proper quoting and escaping and writes them back to the filesystem. While RegEx is not the best solution but it gets the job done.

### What if this corrupts my .env file?

[](#what-if-this-corrupts-my-env-file)

Well, it shouldn't. It uses proper quoting and escaping before writing the values. If you want to make sure it generates a valid file, well, that's why tests are for. You can clone the repo and run `composer install` and then `phpunit` to run the tests. The goal of this library is to generate a `.env` file that can be parsed without any errors using: [vlucas/phpdotenv ](https://github.com/vlucas/phpdotenv)

### How does it handle invalid `.env` files?

[](#how-does-it-handle-invalid-env-files)

It doesn't. You see, it doesn't concern itself with validation of existing values. It simply replaces them via RegEx, and makes sure the changes that it has made is valid. But if you have an existing invalid file, it can do nothing to validate or fix that.

### Can I use this to read values from an .env file?

[](#can-i-use-this-to-read-values-from-an-env-file)

Yes, you can. But you really shouldn't. Thus they aren't documented. This library is for writing to the file. To properly read and load values from `.env` files, use something robust like: [vlucas/phpdotenv ](https://github.com/vlucas/phpdotenv).

Contributing
------------

[](#contributing)

Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.

Please make sure to update tests as appropriate.

License
-------

[](#license)

The library is inspired by and uses some RegEx from the [msztorc/laravel-env](https://github.com/msztorc/laravel-env) package and is based on the same [MIT](https://github.com/MirazMac/DotEnvWriter/blob/master/LICENSE) license.

###  Health Score

50

—

FairBetter than 96% of packages

Maintenance86

Actively maintained with recent releases

Popularity43

Moderate usage in the ecosystem

Community24

Small or concentrated contributor base

Maturity40

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 72% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~267 days

Recently: every ~230 days

Total

7

Last Release

74d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/f7e0cdba7ce3998a3f575d9010e3f10fd9943a8c6212dd7b63e89fb6c58f81e9?d=identicon)[mirazmac](/maintainers/mirazmac)

---

Top Contributors

[![MirazMac](https://avatars.githubusercontent.com/u/13865787?v=4)](https://github.com/MirazMac "MirazMac (18 commits)")[![mariomeyer](https://avatars.githubusercontent.com/u/867650?v=4)](https://github.com/mariomeyer "mariomeyer (3 commits)")[![basteyy](https://avatars.githubusercontent.com/u/2758879?v=4)](https://github.com/basteyy "basteyy (1 commits)")[![brandonferens](https://avatars.githubusercontent.com/u/1819546?v=4)](https://github.com/brandonferens "brandonferens (1 commits)")[![jnunez-aramisgroup](https://avatars.githubusercontent.com/u/35374147?v=4)](https://github.com/jnunez-aramisgroup "jnunez-aramisgroup (1 commits)")[![ntoombs19](https://avatars.githubusercontent.com/u/1688173?v=4)](https://github.com/ntoombs19 "ntoombs19 (1 commits)")

---

Tags

environmentenvvariablesdot envdot env writer

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/mirazmac-dotenvwriter/health.svg)

```
[![Health](https://phpackages.com/badges/mirazmac-dotenvwriter/health.svg)](https://phpackages.com/packages/mirazmac-dotenvwriter)
```

###  Alternatives

[vlucas/phpdotenv

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

13.5k602.4M5.4k](/packages/vlucas-phpdotenv)[symfony/dotenv

Registers environment variables from a .env file

3.8k226.7M2.3k](/packages/symfony-dotenv)[imliam/laravel-env-set-command

Set a .env file variable from the command line

118352.4k10](/packages/imliam-laravel-env-set-command)[msztorc/laravel-env

Laravel env helper commands

7855.4k](/packages/msztorc-laravel-env)[cekurte/environment

A library to get the values from environment variables and process to php data types

5884.0k7](/packages/cekurte-environment)[diarmuidie/envpopulate

Tool to interactively populate a `.env` file based on an `.env.example` file whenever Composer installs or updates.

1892.0k](/packages/diarmuidie-envpopulate)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
