From 1aa2f01d9497de26f59ba1f570f2df33c282bf72 Mon Sep 17 00:00:00 2001 From: Aaron Parecki Date: Sat, 5 Mar 2016 12:28:41 -0800 Subject: [PATCH] convert hostnames to lowercase --- lib/helpers.php | 21 +++++++++++++++++++-- tests/HelpersTest.php | 16 ++++++++++++++++ 2 files changed, 35 insertions(+), 2 deletions(-) create mode 100644 tests/HelpersTest.php diff --git a/lib/helpers.php b/lib/helpers.php index 00e55d5..dbd8522 100644 --- a/lib/helpers.php +++ b/lib/helpers.php @@ -5,9 +5,26 @@ function view($template, $data=[]) { return $templates->render($template, $data); } -// Adds slash if no path is in the URL +// Adds slash if no path is in the URL, and convert hostname to lowercase function normalize_url($url) { - return parse_url($url, PHP_URL_PATH) == '' ? $url.'/' : $url; + $parts = parse_url($url); + if(empty($parts['path'])) + $parts['path'] = '/'; + $parts['host'] = strtolower($parts['host']); + return build_url($parts); +} + +function build_url($parsed_url) { + $scheme = isset($parsed_url['scheme']) ? $parsed_url['scheme'] . '://' : ''; + $host = isset($parsed_url['host']) ? $parsed_url['host'] : ''; + $port = isset($parsed_url['port']) ? ':' . $parsed_url['port'] : ''; + $user = isset($parsed_url['user']) ? $parsed_url['user'] : ''; + $pass = isset($parsed_url['pass']) ? ':' . $parsed_url['pass'] : ''; + $pass = ($user || $pass) ? "$pass@" : ''; + $path = isset($parsed_url['path']) ? $parsed_url['path'] : ''; + $query = isset($parsed_url['query']) ? '?' . $parsed_url['query'] : ''; + $fragment = isset($parsed_url['fragment']) ? '#' . $parsed_url['fragment'] : ''; + return "$scheme$user$pass$host$port$path$query$fragment"; } function should_follow_redirects($url) { diff --git a/tests/HelpersTest.php b/tests/HelpersTest.php new file mode 100644 index 0000000..4336bcb --- /dev/null +++ b/tests/HelpersTest.php @@ -0,0 +1,16 @@ +assertEquals('http://example.com/', $result); + } + + public function testAddsSlashToBareDomain() { + $url = 'http://example.com'; + $result = normalize_url($url); + $this->assertEquals('http://example.com/', $result); + } + +}