selfphp / env-schema
Validate .env environment variables in PHP using a declarative schema.
Installs: 1
Dependents: 0
Suggesters: 0
Security: 0
Stars: 0
Watchers: 0
Forks: 0
Open Issues: 0
pkg:composer/selfphp/env-schema
Requires
- php: >=8.1
Requires (Dev)
- phpstan/phpstan: ^2.1
- phpunit/phpunit: ^12.1
README
env-schema is a lightweight PHP library for validating .env files using a declarative schema.
โ Features
- Validate environment variables at runtime
- Supports types:
string,int,bool,float - Optional fields with
default - Required fields with
required - Allowed values (
allowed) and regex (pattern) checks - Fully tested (PHPUnit 12)
- No dependencies
๐ฆ Installation
composer require selfphp/env-schema
๐งช Usage
.env
APP_ENV=production
DEBUG=true
PORT=8080
APP_SECRET=abcd1234efgh5678ijkl9012mnop3456
schema.php
use Selfphp\EnvSchema\EnvSchema; $schema = [ 'APP_ENV' => [ 'type' => 'string', 'default' => 'production', 'allowed' => ['dev', 'test', 'production'], ], 'DEBUG' => [ 'type' => 'bool', 'default' => false, ], 'PORT' => [ 'type' => 'int', 'required' => true, ], 'APP_SECRET' => [ 'type' => 'string', 'pattern' => '/^[A-Za-z0-9]{32}$/', 'required' => true, ], ]; $validatedEnv = EnvSchema::validate($schema, __DIR__ . '/.env'); echo $validatedEnv['PORT']; // 8080
๐ Example Files
.envโ runtime environment.env.exampleโ template for others.gitignoreโ excludes secrets
๐ License
MIT License ยฉ2025 SELFPHP - Damir Enseleit
๐ฅ๏ธ Run CLI Example
You can quickly test your .env file and schema using the provided example script:
php examples/validate-env.php
This script:
- Loads a predefined schema
- Parses your
.envfile - Outputs all validated values or detailed error messages
Example Output
โ
.env file is valid.
APP_ENV = 'production'
DEBUG = true
PORT = 8080
APP_SECRET = 'abcd1234efgh5678ijkl9012mnop3456'
If validation fails, you'll see helpful errors like:
โ Validation error: Missing required variable: PORT
โน๏ธ Make sure to install dependencies first via
composer install.