📡 You're offline — showing cached content
New version available!
Quick Access
Tutorials PHP for Beginners Environment Variables

Environment Variables

4 min read
Environment variables store sensitive config like passwords outside your source code. Use the phpdotenv library to load a .env file in development. Never commit your .env file — add it to .gitignore immediately.

Environment Variables

// Read from system
$dbUrl = getenv("DATABASE_URL");
$debug = getenv("APP_DEBUG") === "true";

// Using $_ENV superglobal
$secret = $_ENV["APP_SECRET"] ?? "default";

// Using vlucas/phpdotenv (recommended)
// composer require vlucas/phpdotenv

use Dotenv\Dotenv;

$dotenv = Dotenv::createImmutable(__DIR__);
$dotenv->load();
$dotenv->required(["DB_HOST", "DB_NAME", "DB_USER"]);

// .env file
// DB_HOST=localhost
// DB_NAME=myapp
// DB_USER=root
// DB_PASS=secret
// APP_DEBUG=false

$host = $_ENV["DB_HOST"];