1. <?php
  2. /**
  3. * Batch Environment Variable Operations for Isolated Environments
  4. * Designed for limited memory usage and efficient batch processing.
  5. *
  6. * @param array $operations An array of environment variable operations.
  7. * Each element should be an associative array with:
  8. * - 'key': The environment variable key (string).
  9. * - 'operation': The operation to perform ('set' or 'get').
  10. * - 'value': The value to set the variable to (string, optional for 'get').
  11. */
  12. function batchEnvOperations(array $operations): void
  13. {
  14. // Use a file to store environment variables if memory is a concern.
  15. $envFile = 'env_isolated.txt';
  16. // Check if the environment file exists, create it if not.
  17. if (!file_exists($envFile)) {
  18. file_put_contents($envFile, ''); // Create empty file
  19. }
  20. foreach ($operations as $operation) {
  21. $key = $operation['key'];
  22. $operationType = $operation['operation'];
  23. $value = $operation['value'] ?? null; // Optional value
  24. if ($operationType === 'set') {
  25. // Write to the file
  26. $envContent = file_get_contents($envFile) . "\n" . $key . "=" . escapeshellarg($value);
  27. file_put_contents($envFile, $envContent); // Append to the file
  28. } elseif ($operationType === 'get') {
  29. // Read from the file
  30. if (file_exists($envFile)) {
  31. $content = file_get_contents($envFile);
  32. if (strpos($content, $key . "=") !== false) {
  33. $parts = explode("=", $content);
  34. if (count($parts) > 1) {
  35. $envValue = trim($parts[1]); // Remove leading/trailing whitespace
  36. //Set the environment variable
  37. putenv($key . "=" . $envValue);
  38. //echo "Environment variable '$key' set to '$envValue'.\n"; //For debugging
  39. }
  40. }
  41. }
  42. }
  43. }
  44. }
  45. //Example Usage (for testing):
  46. /*
  47. $operations = [
  48. ['key' => 'MY_VARIABLE', 'operation' => 'set', 'value' => 'my_value'],
  49. ['key' => 'ANOTHER_VAR', 'operation' => 'get'],
  50. ['key' => 'MY_VARIABLE', 'operation' => 'get'],
  51. ['key' => 'TEMP_VAR', 'operation' => 'set', 'value' => 'temp_value'],
  52. ];
  53. batchEnvOperations($operations);
  54. //Access the variables:
  55. echo getenv('MY_VARIABLE') . "\n";
  56. echo getenv('ANOTHER_VAR') . "\n";
  57. echo getenv('TEMP_VAR') . "\n";
  58. */
  59. ?>

Add your comment