Environment Variable Secret Pattern (.env file) Regex for PHP
/^((?:[A-Z_]+)?(?:PASSWORD|SECRET|TOKEN|KEY|CREDENTIAL|AUTH|API)[A-Z_]*)=([^\r\n#]{8,})$/mWhat this pattern does
This page provides a comprehensive, battle-tested regular expression for matching environment variable secret pattern (.env file), ported and verified for PHP. In security-sensitive code, using an unverified regex can open the door to both false positives and denial-of-service attacks. The snippet below is ready to drop into your PHP project — whether you're validating in a Laravel validator, a WordPress plugin, or a standalone PHP script.
Php Implementation
<?php
// Environment Variable Secret Pattern (.env file)
// ReDoS-safe | RegexVault — Security > Secrets & Config
define('ENVIRONMENT_VARIABLE_SECRET_PATTERN_ENV_FILE_PATTERN', '/^((?:[A-Z_]+)?(?:PASSWORD|SECRET|TOKEN|KEY|CREDENTIAL|AUTH|API)[A-Z_]*)=([^\r\n#]{8,})$/');
function validate_environment_variable_secret_pattern_env_file(string $input): bool {
return (bool) preg_match(ENVIRONMENT_VARIABLE_SECRET_PATTERN_ENV_FILE_PATTERN, $input);
}
// Example
var_dump(validate_environment_variable_secret_pattern_env_file("DATABASE_PASSWORD=mySecretPassword123")); // bool(true)Test Cases
Matches (Valid) | Rejects (Invalid) |
|---|---|
DATABASE_PASSWORD=mySecretPassword123 | PORT=3000 |
STRIPE_SECRET_KEY=sk_live_4eC39HqLyjWD | NODE_ENV=production |
AWS_SECRET_ACCESS_KEY=wJalrXUtnFEMI/K7MDENG | # PASSWORD_COMMENT=ignored |
| — | SHORT=ab |
When to use this pattern
This pattern is drawn from the Security > Secrets & Config category and carries a ReDoS-safe certification. That matters for PHP developers because especially relevant in PHP where PCRE backtracking limits can trigger silent failures on malicious input. RegexVault audits patterns against known backtracking attack vectors, ensuring you have the necessary context before using this regex in a high-stakes production environment.
Common Pitfalls
Even if .env is in .gitignore, it may be committed before the .gitignore was added, or in a squashed commit. Use git log -- .env to check history. Consider pre-commit hooks that refuse to commit .env files.
Technical Notes
.env files should never be committed to version control. Use .gitignore to exclude .env files. The pattern uses multiline mode to match line-by-line. Capture group 1=key name, group 2=value. Value must be at least 8 chars to reduce false positives.
Have a pattern that belongs in the vault?
Submit it for review — community-verified patterns get credited to your GitHub handle. Free submissions join the queue. Priority review available for $15.
Submit a Pattern