<?php
/**
* Sorts environment variables with fixed retry intervals.
*
* This script iterates through environment variables, sorts them alphabetically,
* and optionally retries setting variables if the initial attempt fails.
*/
// Array to store environment variables
$envVars = getenv();
if ($envVars === false) {
error_log("Failed to retrieve environment variables.");
exit(1);
}
// Sort the environment variables alphabetically
usort($envVars, function ($a, $b) {
return strcmp($a, $b);
});
// Function to set an environment variable with retry
function setEnvWithRetry($varName, $varValue, $maxRetries = 3, $retryInterval = 2) {
$retries = 0;
while ($retries < $maxRetries) {
putenv($varName . "=" . $varValue); // Set the environment variable
if (getenv($varName) === $varValue) { // Check if the variable is set correctly
return true; // Success
}
usleep($retryInterval * 1000000); // Sleep for retry interval in microseconds.
$retries++;
}
error_log("Failed to set environment variable '$varName' after $maxRetries retries.");
return false; // Failure after all retries
}
// Loop through sorted environment variables and set them
foreach ($envVars as $varName => $varValue) {
if (setEnvWithRetry($varName, $varValue)) {
//Variable set successfully
} else {
error_log("Failed to set environment variable: " . $varName);
}
}
echo "Environment variables sorted and set (with retries).";
?>
Add your comment