80 lines
2 KiB
PHP
80 lines
2 KiB
PHP
|
<?php
|
||
|
|
||
|
class UrlManipulator
|
||
|
{
|
||
|
private $paramsArray = ['param1', 'param2', 'param3', 'param4'];
|
||
|
|
||
|
public function manipulateUrl($url)
|
||
|
{
|
||
|
if (!filter_var($url, FILTER_VALIDATE_URL)) {
|
||
|
return ['error' => 'Invalid URL', 'input' => $url];
|
||
|
}
|
||
|
|
||
|
$parsedUrl = parse_url($url);
|
||
|
$existingParams = [];
|
||
|
if (isset($parsedUrl['query'])) {
|
||
|
parse_str($parsedUrl['query'], $existingParams);
|
||
|
}
|
||
|
|
||
|
|
||
|
if (empty($this->paramsArray)) {
|
||
|
return ['error' => 'Params array is full', 'input' => $url];
|
||
|
}
|
||
|
|
||
|
$newParam = $this->getNewParam($existingParams);
|
||
|
|
||
|
if (!$newParam) {
|
||
|
return ['error' => 'Unable to find a unique parameter to add', 'input' => $url];
|
||
|
}
|
||
|
|
||
|
$randomValue = $this->generateRandomValue();
|
||
|
|
||
|
$modifiedUrl = $this->addParamToUrl($url, $newParam, $randomValue);
|
||
|
|
||
|
return [
|
||
|
'before' => $url,
|
||
|
'after' => $modifiedUrl,
|
||
|
];
|
||
|
}
|
||
|
|
||
|
private function addParamToUrl($url, $param, $value)
|
||
|
{
|
||
|
$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;
|
||
|
}
|
||
|
|
||
|
private function generateRandomValue()
|
||
|
{
|
||
|
return uniqid();
|
||
|
}
|
||
|
|
||
|
private function getNewParam($existingParams){
|
||
|
while (!empty($this->paramsArray)) {
|
||
|
$newParam = array_pop($this->paramsArray);
|
||
|
|
||
|
if (!array_key_exists($newParam, $existingParams)) {
|
||
|
return $newParam;
|
||
|
}
|
||
|
}
|
||
|
|
||
|
return null;
|
||
|
}
|
||
|
|
||
|
}
|
||
|
|
||
|
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
|
||
|
$urlManipulator = new UrlManipulator();
|
||
|
$url = $_POST['url'];
|
||
|
$result = $urlManipulator->manipulateUrl($url);
|
||
|
|
||
|
header('Content-Type: application/json');
|
||
|
echo json_encode($result);
|
||
|
}
|