Environment Variables in PHP (No More Hardcoded Secrets)
Store DB credentials and API keys safely using environment variables and .env files.
Chris Howard
September 9, 2025
4.8k213
Hardcoding secrets in code is risky and painful for multi-environment deployments.
Better:
- use environment variables
- optionally load a .env file locally (never commit it)
Example using getenv()
$dbHost = getenv("DB_HOST") ?: "localhost";
$dbName = getenv("DB_NAME") ?: "app";
$dbUser = getenv("DB_USER") ?: "root";
$dbPass = getenv("DB_PASS") ?: "";
.env approach (common)
Many projects use a library (like vlucas/phpdotenv) to load .env into getenv().
Best practice checklist
- .env in local/dev only
- production uses server environment variables
- never commit secrets to git
- rotate keys if leaked
Next: Image processing basics, resize uploads safely.
#PHP#Security#DevOps#Advanced