How to Use PHP putenv to Set Environment Variables
This article explains how to dynamically configure your application
by setting environment variables at runtime using PHP’s built-in
putenv() function. You will learn the correct syntax, see
practical code examples for setting and retrieving variables, and
understand the scope and security implications of using this function in
your web applications.
Understanding putenv() in PHP
The putenv() function adds a value to the current
environment. This environment variable will only exist for the duration
of the current script’s execution and will be cleared once the request
ends.
Syntax
The syntax for putenv() is straightforward. It takes a
single string parameter formatted as a key-value pair:
putenv("KEY=VALUE");To delete an environment variable using putenv(), pass
only the variable name without an equal sign or value:
putenv("KEY");Step-by-Step Code Example
Below is a complete, practical example of how to set an environment
variable at runtime and then retrieve it using the getenv()
function.
<?php
// 1. Set the environment variable
$settingSuccess = putenv("API_KEY=xyz123456789secret");
if ($settingSuccess) {
echo "Environment variable set successfully.<br>";
} else {
echo "Failed to set environment variable.<br>";
}
// 2. Retrieve the environment variable
$apiKey = getenv("API_KEY");
if ($apiKey !== false) {
echo "The API Key is: " . htmlspecialchars($apiKey);
} else {
echo "API Key not found in environment.";
}
?>Key Considerations and Scope
Before implementing putenv() in your production
applications, keep the following rules and behaviors in mind:
- Request Lifetime Scope: Environment variables set
via
putenv()are local to the current request. They do not persist across different users, CLI sessions, or HTTP requests. - Thread Safety: The
putenv()function modifies the environment of the underlying process. If PHP is running in a multi-threaded web server environment (like Apache with the worker MPM), modifying environment variables withputenv()can cause race conditions and is generally considered thread-unsafe. - Superglobals vs. putenv(): Variables defined with
putenv()are not automatically added to the PHP$_ENVor$_SERVERsuperglobal arrays. To access them, you must use thegetenv()function. - Security: Avoid passing unvalidated user input
directly into
putenv(). Doing so can lead to local privilege escalation or unexpected behavior in external libraries that rely on those same environment variables.