<?php
function formatUrl($url)
{
if ( ! is_string($url) || ! $url) {
return '';
}
$info = parse_url($url);
if ( ! $info) {
return '';
}
if (empty($info['scheme']) && strpos($url, '//') === 0) {
$info['scheme'] = is_ssl() ? 'https' : 'http';
}
if (
! isset($info['scheme'])
|| ! isset($info['host'])
|| ! in_array($info['scheme'], ['http', 'https'], true)
) {
return '';
}
$out = $info['scheme'].'://';
$out .= trim(urlencode($info['host']), '/');
if ( ! empty($info['path'])) {
$parts = array_map('urlencode', explode('/', $info['path']));
array_filter($parts);
$out .= '/'.trim(implode('/', $parts), '/');
}
if ( ! empty($info['query'])) {
parse_str($info['query'], $vars);
$parsed = '';
array_walk($vars, function ($v, $k) use (&$parsed) {
$parsed and $parsed .= '&';
$parsed .= "{$k}=".urlencode($v);
});
$vars and $out .= "?{$parsed}";
}
$out = str_replace(
['%22', '%27', '%3E', '%3C'],
['"e;', ''', '>', '<'],
$out
);
return filter_var($out, FILTER_SANITIZE_URL);
}
$test = 'http://look-at-àüß<δmeh.com?foo="bar"&test=:meh!';
echo formatUrl($test);
- Output for 5.5.0 - 5.5.35, 5.6.0 - 5.6.28, 7.0.0 - 7.0.20, 7.1.0 - 7.1.25, 7.2.0 - 7.2.33, 7.3.0 - 7.3.33, 7.4.0 - 7.4.33, 8.0.0 - 8.0.30, 8.1.0 - 8.1.28, 8.2.0 - 8.2.19, 8.3.0 - 8.3.7
- http://look-at-%C3%A0%C3%BC%C3%9F<%CE%B4meh.com?foo="e;bar"e;&test=%3Ameh%21
preferences:
128.22 ms | 404 KiB | 230 Q