PHPackages                             philiprehberger/env-validator - 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. [Validation &amp; Sanitization](/categories/validation)
4. /
5. philiprehberger/env-validator

ActiveLibrary[Validation &amp; Sanitization](/categories/validation)

philiprehberger/env-validator
=============================

Validate required environment variables with type checking and defaults

v1.0.2(1mo ago)11[1 PRs](https://github.com/philiprehberger/env-validator/pulls)MITPHPPHP ^8.2CI passing

Since Mar 13Pushed 1mo agoCompare

[ Source](https://github.com/philiprehberger/env-validator)[ Packagist](https://packagist.org/packages/philiprehberger/env-validator)[ Docs](https://github.com/philiprehberger/env-validator)[ RSS](/packages/philiprehberger-env-validator/feed)WikiDiscussions main Synced 1mo ago

READMEChangelogDependencies (3)Versions (4)Used By (0)

PHP Env Validator
=================

[](#php-env-validator)

[![Tests](https://github.com/philiprehberger/env-validator/actions/workflows/tests.yml/badge.svg)](https://github.com/philiprehberger/env-validator/actions/workflows/tests.yml)[![Latest Version on Packagist](https://camo.githubusercontent.com/800ac85cf523478a3298b230ee49342052150d84383f1df36bb8a40729681dce/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f7068696c69707265686265726765722f656e762d76616c696461746f722e737667)](https://packagist.org/packages/philiprehberger/env-validator)[![License](https://camo.githubusercontent.com/b34688cbb5d47eea5010eaa56b4b287317b11ace3371db7e163dbf03a2dfe4f1/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f6c6963656e73652f7068696c69707265686265726765722f656e762d76616c696461746f72)](LICENSE)

Validate required environment variables with type checking and defaults.

Requirements
------------

[](#requirements)

- PHP 8.2+

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

[](#installation)

```
composer require philiprehberger/env-validator
```

Usage
-----

[](#usage)

### Required Variables

[](#required-variables)

Check that environment variables are present:

```
use PhilipRehberger\EnvValidator\EnvValidator;

$result = EnvValidator::required(['APP_KEY', 'DATABASE_URL', 'REDIS_HOST'])
    ->validate();

if (!$result->passed) {
    echo 'Missing: ' . implode(', ', $result->missing);
}
```

### Schema with Type Rules

[](#schema-with-type-rules)

Define variables with type validation in a single call:

```
$result = EnvValidator::schema([
    'APP_PORT' => 'int',
    'APP_DEBUG' => 'bool',
    'APP_URL' => 'url',
    'ADMIN_EMAIL' => 'email',
])->validate();
```

### Default Values

[](#default-values)

Provide fallback values for variables that may not be set:

```
$result = EnvValidator::required(['APP_PORT', 'APP_ENV'])
    ->defaults([
        'APP_PORT' => '8080',
        'APP_ENV' => 'production',
    ])
    ->validate();
```

### Optional Variables

[](#optional-variables)

Optional variables generate warnings but do not cause validation failure:

```
$result = EnvValidator::required(['DATABASE_URL'])
    ->optional(['CACHE_DRIVER', 'QUEUE_CONNECTION'])
    ->validate();

// $result->warnings contains notices about unset optional vars
```

### Type Validation

[](#type-validation)

Add type rules to individual variables:

```
$result = EnvValidator::required(['API_PORT', 'API_URL'])
    ->type('API_PORT', 'int')
    ->type('API_URL', 'url')
    ->validate();
```

### Validate or Fail

[](#validate-or-fail)

Throw an exception if validation fails:

```
use PhilipRehberger\EnvValidator\Exceptions\EnvValidationException;

try {
    EnvValidator::required(['APP_KEY', 'DATABASE_URL'])
        ->validateOrFail();
} catch (EnvValidationException $e) {
    echo $e->getMessage();
    // Access the full result
    $result = $e->result;
}
```

### Supported Types

[](#supported-types)

TypeDescription`string`Always passes (any string value)`int`, `integer`Numeric digits, optionally prefixed with `-``float`, `number`Any numeric value (uses `is_numeric`)`bool`, `boolean``true`, `false`, `1`, `0`, `yes`, `no` (case-insensitive)`url`Valid URL (uses `FILTER_VALIDATE_URL`)`email`Valid email (uses `FILTER_VALIDATE_EMAIL`)`json`Valid JSON stringAPI
---

[](#api)

### `EnvValidator`

[](#envvalidator)

MethodDescription`required(array $vars): PendingValidation`Define required environment variables`schema(array $rules): PendingValidation`Define variables with type rules### `PendingValidation`

[](#pendingvalidation)

MethodDescription`optional(array $vars): self`Add optional variables (warnings only)`defaults(array $defaults): self`Set default values for missing variables`type(string $var, string $type): self`Add a type rule for a variable`validate(): ValidationResult`Run validation and return result`validateOrFail(): void`Run validation, throw on failure### `ValidationResult`

[](#validationresult)

PropertyTypeDescription`passed``bool`Whether validation passed`missing``array`List of missing required variables`invalid``array`Map of variable names to error messages`warnings``array`List of warning messages`toArray()``array`Convert result to arrayDevelopment
-----------

[](#development)

```
composer install
vendor/bin/phpunit
vendor/bin/pint --test
vendor/bin/phpstan analyse
```

License
-------

[](#license)

MIT

###  Health Score

39

—

LowBetter than 86% of packages

Maintenance89

Actively maintained with recent releases

Popularity4

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity48

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% 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 ~2 days

Total

3

Last Release

54d ago

### Community

Maintainers

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

---

Top Contributors

[![philiprehberger](https://avatars.githubusercontent.com/u/8218077?v=4)](https://github.com/philiprehberger "philiprehberger (10 commits)")

---

Tags

validatorvalidationenvironmentenvdotenv

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Code StyleLaravel Pint

Type Coverage Yes

### Embed Badge

![Health badge](/badges/philiprehberger-env-validator/health.svg)

```
[![Health](https://phpackages.com/badges/philiprehberger-env-validator/health.svg)](https://phpackages.com/packages/philiprehberger-env-validator)
```

###  Alternatives

[respect/validation

The most awesome validation engine ever created for PHP

5.9k37.4M383](/packages/respect-validation)[opis/json-schema

Json Schema Validator for PHP

64236.9M185](/packages/opis-json-schema)[vlucas/valitron

Simple, elegant, stand-alone validation library with NO dependencies

1.6k4.4M128](/packages/vlucas-valitron)[intervention/validation

Additional validation rules for the Laravel framework

6826.7M8](/packages/intervention-validation)[proengsoft/laravel-jsvalidation

Validate forms transparently with Javascript reusing your Laravel Validation Rules, Messages, and FormRequest

1.1k2.3M49](/packages/proengsoft-laravel-jsvalidation)[wixel/gump

A fast, extensible &amp; stand-alone PHP input validation class that allows you to validate any data.

1.2k1.3M29](/packages/wixel-gump)

PHPackages © 2026

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