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.2.0(2mo ago)138MITPHPPHP ^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)[ GitHub Sponsors](https://github.com/philiprehberger)[ RSS](/packages/philiprehberger-env-validator/feed)WikiDiscussions main Synced 3w ago

READMEChangelogDependencies (6)Versions (6)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)[![Last updated](https://camo.githubusercontent.com/a94588951638f8b6476064ed159c9c8ea31490c37d0783076602f57d62f6bb6d/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f6c6173742d636f6d6d69742f7068696c69707265686265726765722f656e762d76616c696461746f72)](https://github.com/philiprehberger/env-validator/commits/main)

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;
}
```

### IP Validation

[](#ip-validation)

Validate IP addresses with specific version constraints:

```
$result = EnvValidator::required(['SERVER_IP', 'GATEWAY_V4', 'GATEWAY_V6'])
    ->type('SERVER_IP', 'ip')
    ->type('GATEWAY_V4', 'ipv4')
    ->type('GATEWAY_V6', 'ipv6')
    ->validate();
```

### Custom Validation Rules

[](#custom-validation-rules)

Define your own validation logic with a callable:

```
$result = EnvValidator::required(['APP_SECRET'])
    ->custom('APP_SECRET', fn (string $value) => strlen($value) >= 32, 'Secret must be at least 32 characters.')
    ->validate();
```

### Enum Validation

[](#enum-validation)

Validate that a value matches one of a backed enum's cases:

```
enum Environment: string
{
    case Production = 'production';
    case Staging = 'staging';
    case Development = 'development';
}

$result = EnvValidator::required(['APP_ENV'])
    ->enum('APP_ENV', Environment::class)
    ->validate();
```

### Dependency Rules

[](#dependency-rules)

Make variables conditionally required based on other variables:

```
// DB_HOST is only required when DB_DRIVER is set
$result = EnvValidator::required(['DB_DRIVER', 'DB_HOST'])
    ->dependsOn('DB_HOST', 'DB_DRIVER')
    ->validate();

// REDIS_HOST is required when CACHE_DRIVER equals "redis"
$result = EnvValidator::required(['CACHE_DRIVER', 'REDIS_HOST'])
    ->requiredIf('REDIS_HOST', 'CACHE_DRIVER', 'redis')
    ->validate();

// APP_SECRET is required unless APP_ENV equals "local"
$result = EnvValidator::required(['APP_ENV', 'APP_SECRET'])
    ->requiredUnless('APP_SECRET', 'APP_ENV', 'local')
    ->validate();
```

### .env File Parsing

[](#env-file-parsing)

Validate a `.env` file without loading it into the environment:

```
$result = EnvValidator::fromFile('/path/to/.env')
    ->type('APP_PORT', 'int')
    ->type('APP_URL', 'url')
    ->validate();
```

The parser handles comments, quoted values, multiline values, `export` prefix, and `${VAR}` interpolation.

### Environment Profiles

[](#environment-profiles)

Register named validation profiles for different environments:

```
// Register profiles
EnvValidator::profile('web', [
    'APP_URL' => 'url',
    'APP_PORT' => 'int',
    'APP_DEBUG' => 'bool',
]);

EnvValidator::profile('worker', [
    'QUEUE_CONNECTION' => 'string',
    'REDIS_HOST' => 'string',
]);

// Validate against a profile
$result = EnvValidator::validateProfile('web');
```

### 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`)`ip`Valid IP address (uses `FILTER_VALIDATE_IP`)`ipv4`Valid IPv4 address`ipv6`Valid IPv6 address`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`fromFile(string $path): PendingFileValidation`Validate a .env file without loading it`profile(string $name, array $schema): void`Register a named validation profile`validateProfile(string $name): ValidationResult`Validate against a named profile### `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`custom(string $var, callable $validator, string $message = ''): self`Add a custom validation rule`enum(string $var, string $enumClass): self`Validate against a backed enum`dependsOn(string $var, string $dependency): self`Require variable only when dependency is set`requiredIf(string $var, string $conditionVar, mixed $value): self`Require variable when condition equals value`requiredUnless(string $var, string $conditionVar, mixed $value): self`Require variable unless condition equals value`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
```

Support
-------

[](#support)

If you find this project useful:

⭐ [Star the repo](https://github.com/philiprehberger/env-validator)

🐛 [Report issues](https://github.com/philiprehberger/env-validator/issues?q=is%3Aissue+is%3Aopen+label%3Abug)

💡 [Suggest features](https://github.com/philiprehberger/env-validator/issues?q=is%3Aissue+is%3Aopen+label%3Aenhancement)

❤️ [Sponsor development](https://github.com/sponsors/philiprehberger)

🌐 [All Open Source Projects](https://philiprehberger.com/open-source-packages)

💻 [GitHub Profile](https://github.com/philiprehberger)

🔗 [LinkedIn Profile](https://www.linkedin.com/in/philiprehberger)

License
-------

[](#license)

[MIT](LICENSE)

###  Health Score

41

—

FairBetter than 87% of packages

Maintenance88

Actively maintained with recent releases

Popularity9

Limited adoption so far

Community8

Small or concentrated contributor base

Maturity50

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 94.7% 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 ~4 days

Total

5

Last Release

86d 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 (18 commits)")[![dependabot[bot]](https://avatars.githubusercontent.com/in/29110?v=4)](https://github.com/dependabot[bot] "dependabot[bot] (1 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

6.0k39.0M407](/packages/respect-validation)[opis/json-schema

Json Schema Validator for PHP

64941.2M260](/packages/opis-json-schema)[vlucas/valitron

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

1.6k4.6M135](/packages/vlucas-valitron)[intervention/validation

Additional validation rules for the Laravel framework

6777.1M18](/packages/intervention-validation)[proengsoft/laravel-jsvalidation

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

1.1k2.3M50](/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.4M31](/packages/wixel-gump)

PHPackages © 2026

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