Created
September 4, 2017 09:16
-
-
Save jornane/1af670caac4ad029e3b5a861eeda1c83 to your computer and use it in GitHub Desktop.
URL parser
This file contains 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 | |
function getRedirectTo(string $appBaseUrl, $server, $redirectTo = ''): string { | |
$returnUrlData = strlen($redirectTo) > 0 | |
? parse_url($redirectTo, PHP_URL_SCHEME|PHP_URL_HOST|PHP_URL_PORT|PHP_URL_PATH|PHP_URL_QUERY|PHP_URL_FRAGMENT) | |
: [] | |
; | |
$appBaseUrlParsed = parse_url($appBaseUrl, PHP_URL_SCHEME|PHP_URL_HOST|PHP_URL_PORT|PHP_URL_PATH|PHP_URL_QUERY|PHP_URL_FRAGMENT) | |
if (!array_key_exists($returnUrlData, 'scheme')) { | |
if (array_key_exists($appBaseUrlParsed, 'scheme')) { | |
$returnUrlData['scheme'] = $appBaseUrlParsed['scheme']; | |
} else { | |
$returnUrlData['scheme'] = guessHTTPS($server); | |
} | |
} | |
if (!array_key_exists($returnUrlData, 'host')) { | |
if (array_key_exists($appBaseUrlParsed, 'host')) { | |
$returnUrlData['host'] = $appBaseUrlParsed['host']; | |
if (array_key_exists($appBaseUrlParsed, 'port')) { | |
$returnUrlData['port'] = $appBaseUrlParsed['port']; | |
} | |
} else { | |
$returnUrlData['host'] = $server['HTTP_HOST']; | |
$returnUrlData['port'] = $server['SERVER_PORT']; | |
} | |
} | |
if (array_key_exists($returnUrlData, 'port')) { | |
if ($returnUrlData['port'] == 80 && $returnUrlData['scheme'] === 'http') unset($returnUrlData['port']); | |
if ($returnUrlData['port'] == 443 && $returnUrlData['scheme'] === 'https') unset($returnUrlData['port']); | |
} | |
if (!array_key_exists($returnUrlData, 'path')) { | |
if (array_key_exists($appBaseUrlParsed, 'path')) { | |
$returnUrlData['path'] = $appBaseUrlParsed['path']; | |
$returnUrlData['query'] = $appBaseUrlParsed['query']; | |
} else { | |
$returnUrlData['path'] = strstr($_SERVER['REQUEST_URI'], '?', true); | |
$returnUrlData['query'] = $_SERVER['QUERY_STRING']; | |
} | |
} | |
} | |
function guessHTTPS($server): string { | |
if (!array_key_exists($server, 'HTTPS')) | |
return 'http'; | |
if ($server['HTTPS'] === 'off') | |
return 'http'; | |
return empty($server['HTTPS']) ? 'http' : 'https'; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment