It's strange that PHP currently doesn't have a function to encode the entire URL, including domain/path/query. My version to encode Full url.
/**
* To encode full url including domain/path/query
* https://www.php.net/manual/en/function.parse-url.php
* https://www.php.net/en/idn_to_ascii
* https://www.php.net/manual/en/function.urlencode.php
*
* @param string $urlFull
* @return string
*/
function urlencodeFull(string $urlFull): string
{
//add scheme if not set
$urlFull = ((!strstr($urlFull, '://') and strlen($urlFull)) ? 'https://' : '') . $urlFull;
//parse url
if($url = parse_url($urlFull) and isset($url['host']))
{
//urlencode for url path
if(isset($url['path']) and strlen($url['path']) > 1)
{
$url['pathArray'] = array_filter(array_map(fn($v) => urlencode(urldecode($v)), explode('/', $url['path'])));
}
//urlencode for url query
if(isset($url['query']) and strlen($url['query']) > 1)
{
$url['queryArray'] = array_filter(array_map(fn($v) => urlencode(urldecode($v)), explode('&', $url['query'])));
}
return $url['scheme'] . '://' . idn_to_ascii($url['host']) .
(isset($url['port']) ? ':' . $url['port'] : '') .
(isset($url['pathArray']) ? '/' . implode('/', $url['pathArray']) . '/' : '') .
(isset($url['queryArray']) ? '?' . implode('&', $url['queryArray']) : '') .
(isset($url['fragment']) ? '#' . $url['fragment'] : '');
}
else
{
return $urlFull;
}
}
And in result:
echo urlencodeFull('https://täst.de/täst1/täst2?täst3=t r u e');
will be
https://xn--tst-qla.de/t%C3%A4st1/t%C3%A4st2/?t%C3%A4st3%3Dt+r+u+e