Skip to content

Instantly share code, notes, and snippets.

@dotancohen
Last active September 4, 2018 09:55
Show Gist options
  • Save dotancohen/b96bcd425afe4f15eadd7c470e39f2a8 to your computer and use it in GitHub Desktop.
Save dotancohen/b96bcd425afe4f15eadd7c470e39f2a8 to your computer and use it in GitHub Desktop.
<?php
/**
* Properly format a user-entered URL for use in an href or src attribute.
*
* @param string $url User-entered URL
* @return string Formatted URL
*/
function url_esc(string $url) : string
{
$out = '';
$query = '';
$u = parse_url($url);
if ( !empty($u['query']) ) {
parse_str($u['query'], $qs);
$query = '?' . http_build_query($qs, '&', '', PHP_QUERY_RFC3986);
}
$out .= !empty($u['scheme']) ? $u['scheme'].'://' : '';
$out .= !empty($u['user']) ? $u['user'] . ( !empty($u['pass']) ? ':'.$u['pass'] : '') . '@' : '';
$out .= $u['host'] ?? '';
$out .= !empty($u['port']) ? ':'.$u['port'] : '';
$out .= $u['path'] ?? '';
$out .= $query;
$out .= !empty($u['fragment']) ? '#'.$u['fragment'] : '';
return filter_var($out, FILTER_SANITIZE_URL);
}
$foo = "https://user:pass@www.example.com:80/foo/bar.php?aa=דותן כהןׁ&cc=this is a variable#fragment";
var_dump($foo, url_esc($foo));
echo "\n";
$foo = "https://user@www.example.com/foo/bar.php?aa=דותן כהןׁ&cc=this is a variable#fragment";
var_dump($foo, url_esc($foo));
echo "\n";
$foo = "https://www.example.com/foo/bar.php?aa=דותן כהןׁ&cc=this is a variable#fragment";
var_dump($foo, url_esc($foo));
echo "\n";
$foo = "www.example.com/foo/bar.php?aa=דותן כהןׁ&cc=this is a variable#fragment";
var_dump($foo, url_esc($foo));
echo "\n";
$foo = "/foo/bar.php?aa=דותן כהןׁ&cc=this is a variable#fragment";
var_dump($foo, url_esc($foo));
echo "\n";
$foo = "foo/bar.php?aa=דותן כהןׁ&cc=this is a variable#fragment";
var_dump($foo, url_esc($foo));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment