getNewParam($usedParams, $originalUrl); // If no new parameter is found, return an error if (!$newParam) { return ['error' => 'Unable to find a unique parameter to add', 'input' => $url]; } $randomValue = $this->generateRandomValue(); $modifiedUrl = $this->addParamToUrl($originalUrl, $newParam, $randomValue); // Store the used parameter in the session $usedParams[] = $newParam; $_SESSION['usedParams'] = $usedParams; return [ 'before' => $originalUrl, 'after' => $modifiedUrl, ]; } protected function addParamToUrl(string $url, string $param, string $value): string { $separator = (parse_url($url, PHP_URL_QUERY) == null) ? '?' : '&'; if (strpos($url, $param . '=') !== false) { $modifiedUrl = preg_replace('/(' . $param . '=)[^&]+/', '$1' . urlencode($value), $url); } else { $modifiedUrl = $url . $separator . urlencode($param) . '=' . urlencode($value); } return $modifiedUrl; } protected function generateRandomValue(): string { return uniqid(); } protected function getNewParam(array $usedParams, string $originalUrl) { $parsedUrl = parse_url($originalUrl); $existingParams = []; // Extract existing params from the original URL if (isset($parsedUrl['query'])) { parse_str($parsedUrl['query'], $existingParams); } // Find the first unused parameter from the predefined array and existing parameters foreach ($this->paramsArray as $param) { if (!in_array($param, $usedParams) && !array_key_exists($param, $existingParams)) { return $param; } } return null; } }