A database password, an API key, or a setting that differs between a local machine and a live server doesn't belong hardcoded in a PHP file — an environment variable keeps it outside the codebase entirely.
$dbHost = getenv('DB_HOST');
$dbPassword = getenv('DB_PASSWORD');
// or, depending on server configuration:
$dbHost = $_ENV['DB_HOST'] ?? $_SERVER['DB_HOST'];A plain text file, kept out of version control, listing key-value pairs — the standard way to set environment variables on a local machine without configuring the whole OS.
# .env
DB_HOST=localhost
DB_NAME=myapp
DB_USER=root
DB_PASSWORD=secret123
API_KEY=sk_test_abc123PHP doesn't read .env files natively — the standard package for it, installed via Composer, loads the file's values into getenv()/$_ENV.
composer require vlucas/phpdotenvrequire 'vendor/autoload.php';
$dotenv = Dotenv\Dotenv::createImmutable(__DIR__);
$dotenv->load();
echo getenv('DB_HOST'); // localhost# .gitignore
.envThe most important habit in this lesson
A .env file committed to a public repository is one of the most common real-world causes of a leaked API key or database password — add it to .gitignore from the very first commit, not after the fact.
A version of the file with the keys but placeholder values, committed to the repo — shows every teammate what variables are needed, without exposing any real secret.
# .env.example — safe to commit
DB_HOST=localhost
DB_NAME=
DB_USER=
DB_PASSWORD=
API_KEY=