1. <?php
  2. /**
  3. * Sorts environment variables with fixed retry intervals.
  4. *
  5. * This script iterates through environment variables, sorts them alphabetically,
  6. * and optionally retries setting variables if the initial attempt fails.
  7. */
  8. // Array to store environment variables
  9. $envVars = getenv();
  10. if ($envVars === false) {
  11. error_log("Failed to retrieve environment variables.");
  12. exit(1);
  13. }
  14. // Sort the environment variables alphabetically
  15. usort($envVars, function ($a, $b) {
  16. return strcmp($a, $b);
  17. });
  18. // Function to set an environment variable with retry
  19. function setEnvWithRetry($varName, $varValue, $maxRetries = 3, $retryInterval = 2) {
  20. $retries = 0;
  21. while ($retries < $maxRetries) {
  22. putenv($varName . "=" . $varValue); // Set the environment variable
  23. if (getenv($varName) === $varValue) { // Check if the variable is set correctly
  24. return true; // Success
  25. }
  26. usleep($retryInterval * 1000000); // Sleep for retry interval in microseconds.
  27. $retries++;
  28. }
  29. error_log("Failed to set environment variable '$varName' after $maxRetries retries.");
  30. return false; // Failure after all retries
  31. }
  32. // Loop through sorted environment variables and set them
  33. foreach ($envVars as $varName => $varValue) {
  34. if (setEnvWithRetry($varName, $varValue)) {
  35. //Variable set successfully
  36. } else {
  37. error_log("Failed to set environment variable: " . $varName);
  38. }
  39. }
  40. echo "Environment variables sorted and set (with retries).";
  41. ?>

Add your comment