Back to Blog
Lesson 50 of the PHP: Modern PHP from the Ground Up course
PHPSeptember 7, 20263 min read

Environment Configuration: Mastering .env Files in PHP

Stop hardcoding secrets. Learn how to manage environment configuration with .env files, use environment variables, and keep sensitive data out of Git.

PHPSecurityConfigurationEnvironment VariablesDotenv
A close-up view of PHP code displayed on a computer screen, highlighting programming and development concepts.

Previously in this course, we explored using third-party libraries via Composer to extend our application's functionality. In this lesson, we address a critical security and maintenance requirement: managing configuration data—like database credentials and API keys—independently of your application code.

The Problem with Hardcoded Configuration

Throughout our project, we've been connecting to databases and configuring services by defining variables directly in our PHP files. While this works in development, it creates two major problems:

  1. Security Risk: If you push your code to a public repository (like GitHub), anyone can see your database passwords and API keys.
  2. Environment Mismatch: Your development machine likely uses different database credentials than your production server. Changing these values manually every time you deploy is a recipe for disaster.

The solution is to use environment variables—values that exist outside your code, provided by the server's operating system or a configuration file.

Introducing the .env File

In the PHP ecosystem, the standard way to manage these variables is through a .env file. This is a simple text file that stores key-value pairs.

Create a file named .env in your project root:

TEXT
DB_HOST=localhost
DB_NAME=my_mvc_app
DB_USER=root
DB_PASS=supersecretpassword
API_KEY=xyz123abc

Crucial Step: You must immediately add .env to your .gitignore file. This ensures that your secrets are never committed to version control. To help your team members know what variables are required, create a file named .env.example containing only the keys (without the real values):

TEXT
DB_HOST=localhost
DB_NAME=
DB_USER=
DB_PASS=
API_KEY=

Loading Environment Variables with PHP

PHP doesn't natively parse .env files. We use the vlucas/phpdotenv library, which is the industry standard. Install it via Composer:

Bash
composer require vlucas/phpdotenv

Once installed, initialize it early in your application's entry point (e.g., public/index.php):

PHP
require_once __DIR__ . '/../vendor/autoload.php';

$dotenv = Dotenv\Dotenv::createImmutable(__DIR__ . '/../');
$dotenv->load();

#6A9955">// Now access variables using the $_ENV superglobal
$dbHost = $_ENV['DB_HOST'];

Comparison: Hardcoded vs. Environment Variables

FeatureHardcoded ConfigEnvironment Variables
SecurityLow (exposed in Git)High (kept local/server-side)
FlexibilityRigid (requires code change)Dynamic (change per server)
VersioningCommitted to GitIgnored by Git (.gitignore)
SetupImmediateRequires phpdotenv library

Hands-on Exercise

  1. Move your database credentials from your PDO connection code into a new .env file in your root directory.
  2. Update your .gitignore file to include .env.
  3. Update your Database class or connection logic to read the values using $_ENV['KEY_NAME'].
  4. Verify that your app still connects to the database correctly.

Common Pitfalls

  • Committing the .env file: This is the most common security failure in web development. Always check your git status before pushing to ensure .env is ignored.
  • Assuming variables exist: If a variable is missing from the .env file, $_ENV will return null. Always provide default values or validate that the required keys exist using $dotenv->required(['DB_HOST', 'DB_USER']);.
  • Scope issues: Ensure you call load() before you attempt to access any environment variables.

FAQ

Can I use environment variables for non-sensitive data? Yes. Even for non-sensitive settings like APP_DEBUG=true, using environment variables makes it easier to toggle features between development and production without editing code.

What if I don't want to use a library? You could manually read the file with file_get_contents and putenv, but phpdotenv handles edge cases like quoted strings and comment lines automatically. It is safer to use the established tool.

Recap

We’ve successfully decoupled our configuration from our source code. By using a .env file for local development and setting equivalent environment variables on your production server (a common practice when handling sensitive data), you ensure your credentials remain private and your application remains portable across environments.

Up next: We will learn how to protect our users by sanitizing output and preventing Cross-Site Scripting (XSS) attacks.

Similar Posts