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: