Last active
September 4, 2018 09:55
-
-
Save dotancohen/b96bcd425afe4f15eadd7c470e39f2a8 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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:[email protected]:80/foo/bar.php?aa=דותן כהןׁ&cc=this is a variable#fragment"; | |
var_dump($foo, url_esc($foo)); | |
echo "\n"; | |
$foo = "https://[email protected]/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