What Are Environment Variables in PHP?
Environment variables in PHP are dynamic values that affect the application’s configuration and operation. They exist outside the application code and can be used to set up operational parameters without altering the application’s source code. Environment variables allow developers to toggle between different configurations easily, such as switching from development to production settings.
In PHP, environment variables are often used to store sensitive information such as database credentials, API keys, or other configuration parameters. However, it’s important to note that while environment variables are more secure than hard-coding secrets, they are still stored in plaintext and visible to anyone accessing your systems. This makes it critical to use additional mechanisms, like configuration and secrets management systems, to secure confidential info.
In this article:
Why Use Environment Variables in PHP Applications
Environment variables offer several advantages when managing PHP applications, particularly in dynamic and multi-environment setups:
- Security: Storing sensitive data like database credentials, API keys, and authentication tokens in environment variables is better than hardcoding them in source files, reducing exposure risks. However, environment variables are not fully secure, making it important to use configuration and secrets management systems.
- Configuration flexibility: Developers can switch between environments (development, staging, production) without modifying the application’s code. This makes deployments more efficient and reduces errors.
- Version control safety: Keeping sensitive configuration data outside the codebase ensures that credentials and secrets are not accidentally committed to version control systems like Git.
- Simplified deployment: Environment variables help configure applications consistently across different servers or containerized environments, making deployment automation easier.
- Maintainability: By externalizing configurations, developers can manage settings without modifying the code, improving long-term maintainability and scalability.
How to Access Environment Variables in PHP
PHP provides multiple ways to access environment variables, ensuring flexibility based on the application’s requirements and the runtime environment.
Using PHP’s superglobals
Environment variables can be accessed through PHP’s predefined superglobal arrays. The _SERVER
and $_ENV
arrays store environment-related data, including server configuration details and custom environment variables. However, their availability depends on the variables_order
directive in the PHP configuration.
If this directive does not include “E” (for $_ENV
) or “S” (for $_SERVER
), the arrays may be empty. Additionally, the contents of $_SERVER
and _ENV
may overlap, so checking for conflicts is important.
Using getenv()
The getenv()
function retrieves environment variables directly. When called without arguments, it returns an array of all available environment variables. When given a variable name, it returns that variable’s value.
echo getenv('DATABASE_URL');
One limitation of getenv()
is that, in FastCGI or other SAPI environments, it always returns the value set by the SAPI, even if putenv()
has modified the variable locally. The local_only
parameter can be used to restrict the function to locally set values.
Using apache_getenv()
(for Apache servers)
For applications running on Apache, the apache_getenv()
function provides an alternative way to access environment variables. It retrieves variables set in the Apache process.
echo apache_getenv('SERVER_ADMIN');
Regardless of the method used, environment variables should not be trusted implicitly. They should always be validated and sanitized before use, as they can be manipulated externally depending on the execution environment.
Tips From the Expert
In my experience, here are tips that can help you better manage and optimize environment variables in PHP applications:
- Use configuration caching in production: For large applications, parsing environment variables dynamically can add overhead. Consider caching configurations during the application boot process by converting the .env variables into an optimized configuration file (e.g., JSON or array) to improve performance in production environments.
- Leverage immutable environment variables for critical settings: For settings that should never be changed at runtime (e.g., database host or encryption keys), mark them as immutable. This can be done using libraries like PHP dotenv by loading them as immutable or locking them in a bootstrap process, preventing accidental overrides.
- Control variable scope carefully: Avoid overloading environment variables across the entire application. Instead, segment and scope them per module or service where possible, using environment-specific config objects. This reduces the risk of accidental leakage or unintended usage.
- Use secrets management solutions for sensitive variables: For sensitive variables like API keys and database passwords, consider integrating a secrets manager (e.g., AWS Secrets Manager, HashiCorp Vault) instead of relying solely on .env files. This adds an additional layer of security, with automated rotation and auditing capabilities.
- Set up environment variable injection in CI/CD pipelines: For automated deployments, ensure the CI/CD pipelines inject environment variables dynamically based on the environment being targeted (development, staging, production). This prevents manual errors during deployments and enforces consistency.
Set Environment Variables in PHP with PHP dotenv
PHP dotenv is a library that simplifies managing environment variables in PHP applications. It loads environment variables from a .env
file, making them accessible via getenv()
, _ENV
, and _SERVER
. This approach helps keep sensitive data out of the source code while allowing flexible configuration.
Install PHP dotenv
To use PHP dotenv, install it using Composer:
composer require vlucas/phpdotenv
This command downloads the PHP dotenv package and adds it to the project’s dependencies.
Create a .env
file
In the root directory of the project, create a file named .env
and define the environment variables:
API_KEY=1234567890
This file should not be committed to version control to keep sensitive data secure.
Load environment variables
To load environment variables into the application, modify the main entry file (e.g., public/index.php
) and include the following code:
require __DIR__ . '/vendor/autoload.php';
$dotenv = Dotenv\Dotenv::createImmutable(__DIR__);
$dotenv->load();
This initializes PHP dotenv and loads the variables from the .env
file.
Access environment variables
Once loaded, environment variables can be accessed using _ENV
, _SERVER
, or getenv()
:
$apiKey = $_ENV['API_KEY'] ?? 'default_key';
echo "API Key: " . $apiKey;
Use a custom .env
file
If you want to use a file with a different name, pass the filename as a second parameter:
$dotenv = Dotenv\Dotenv::createImmutable(__DIR__, '.custom_env');
$dotenv->load();
You can also provide multiple filenames:
$dotenv = Dotenv\Dotenv::createImmutable(__DIR__, ['.env', '.env.local']);
$dotenv->load();
Ensure required variables are defined
To enforce the presence of critical environment variables, use the required()
method:
$dotenv->required(['API_KEY']);
To ensure that variables are not empty:
$dotenv->required(['API_KEY'])->notEmpty();
If a required variable is missing or empty, PHP dotenv will throw an exception, preventing the application from running with incorrect configurations.
Related content: Read our guide to PowerShell set environment variable
5 Best Practices for Using Environment Variables in PHP
Here are some useful practices to keep in mind when working with PHP for .env
variables.
1. Avoid Committing Sensitive Data to Version Control
Avoid committing sensitive environment variables to version control systems like Git. Storing API keys, passwords, or any sensitive configuration parameters in a public or shared repository can lead to data breaches and unauthorized access. Use a .gitignore
file to exclude .env
files and similar configuration files from version control, protecting against accidental exposure while preserving flexibility in configuration management.
Use environment-specific configuration files for local development and share a template file (e.g., .env.example
) with placeholder values in repositories. This provides guidance on which variables are needed without revealing sensitive data. Clearly document any required variables to ensure that collaborators know what is needed to run the application properly.
2. Use Environment Variables for Configuration Parameters
Environment variables should be used to manage configuration parameters that might differ between environments. This allows easy toggling between different setups without modifying the application’s source code. Configuration options like database credentials, caching servers, and API endpoints should be managed this way to improve application portability and reduce deployment complexity.
Have the application read all configurations from environment variables at startup. This practice decouples configuration and code, allowing operations teams to adjust application behavior via deployment settings. It simplifies integration with orchestration tools and platforms that may automatically set environment variables during deployment.
3. Validate and Sanitize Environment Variables
Validating and sanitizing environment variables is critical in preventing erroneous application behavior and improving security. Always verify the presence and format of expected environment variables before using them in application logic. Define default values where logical defaults exist to maintain consistent behavior in varied deployments.
Sanitization ensures that inputs from environment variables are free from unwanted characters or formats. Techniques include casting variables to expected data types and checking against regular expressions for patterns. Additionally, log validation failures to track down configuration issues swiftly, and consider using type-safe libraries or functions provided by the language.
4. Document All Required Environment Variables
A detailed guide or documentation section should list each environment variable, explain its purpose, and specify acceptable values or formats. This information is essential for team members who are setting up development environments or deploying the application.
Additionally, maintaining an example configuration file with default or placeholder values can simplify the configuration process for new developers or environments. This ensures clarity, reduces errors, and speeds up onboarding. Documentation should be kept up to date as new variables are added or removed to reflect the current state of the application configuration.
5. Keep Environment-Specific Variables Out of Codebase
Environment-specific variables, when hard-coded, can lead to errors when moving between environments or scaling applications. Instead, use environment variables to encapsulate these differences, enabling smooth transitions and deployments using the same codebase across various environments.
To achieve this, use configuration files that draw from environment variables or leverage orchestration platforms that set environment variables during deployment. This practice promotes a codebase that’s environment-agnostic, improving maintainability and reducing the chances of configuration errors. It allows developers to focus on building features while operations manage deployment-specific configurations.
Managing and Securely Storing Environment Variables with Configu
Configu is a configuration management platform comprised of two main components, the stand-alone Orchestrator, which is open source, and the Cloud, which is a SaaS solution:
Configu Orchestrator
As applications become more dynamic and distributed in microservices architectures, configurations are getting more fragmented. They are saved as raw text that is spread across multiple stores, databases, files, git repositories, and third-party tools (a typical company will have five to ten different stores).
The Configu Orchestrator, which is open-source software, is a powerful standalone tool designed to address this challenge by providing configuration orchestration along with Configuration-as-Code (CaC) approach.
Configu Cloud
Configu Cloud is the most innovative store purpose-built for configurations, including environment variables, secrets, and feature flags. It is built based on the Configu configuration-as-code (CaC) approach and can model configurations and wrap them with unique layers, providing collaboration capabilities, visibility into configuration workflows, and security and compliance standardization.
Unlike legacy tools, which treat configurations as unstructured data or key-value pairs, Configu is leading the way with a Configuration-as-Code approach. By modeling configurations, they are treated as first-class citizens in the developers’ code. This makes our solution more robust and reliable and also enables Configu to provide more capabilities, such as visualization, a testing framework, and security abilities.