<?php
/**
* Batch Environment Variable Operations for Isolated Environments
* Designed for limited memory usage and efficient batch processing.
*
* @param array $operations An array of environment variable operations.
* Each element should be an associative array with:
* - 'key': The environment variable key (string).
* - 'operation': The operation to perform ('set' or 'get').
* - 'value': The value to set the variable to (string, optional for 'get').
*/
function batchEnvOperations(array $operations): void
{
// Use a file to store environment variables if memory is a concern.
$envFile = 'env_isolated.txt';
// Check if the environment file exists, create it if not.
if (!file_exists($envFile)) {
file_put_contents($envFile, ''); // Create empty file
}
foreach ($operations as $operation) {
$key = $operation['key'];
$operationType = $operation['operation'];
$value = $operation['value'] ?? null; // Optional value
if ($operationType === 'set') {
// Write to the file
$envContent = file_get_contents($envFile) . "\n" . $key . "=" . escapeshellarg($value);
file_put_contents($envFile, $envContent); // Append to the file
} elseif ($operationType === 'get') {
// Read from the file
if (file_exists($envFile)) {
$content = file_get_contents($envFile);
if (strpos($content, $key . "=") !== false) {
$parts = explode("=", $content);
if (count($parts) > 1) {
$envValue = trim($parts[1]); // Remove leading/trailing whitespace
//Set the environment variable
putenv($key . "=" . $envValue);
//echo "Environment variable '$key' set to '$envValue'.\n"; //For debugging
}
}
}
}
}
}
//Example Usage (for testing):
/*
$operations = [
['key' => 'MY_VARIABLE', 'operation' => 'set', 'value' => 'my_value'],
['key' => 'ANOTHER_VAR', 'operation' => 'get'],
['key' => 'MY_VARIABLE', 'operation' => 'get'],
['key' => 'TEMP_VAR', 'operation' => 'set', 'value' => 'temp_value'],
];
batchEnvOperations($operations);
//Access the variables:
echo getenv('MY_VARIABLE') . "\n";
echo getenv('ANOTHER_VAR') . "\n";
echo getenv('TEMP_VAR') . "\n";
*/
?>
Add your comment