Skip to content

Instantly share code, notes, and snippets.

@trungpv1601
Forked from aurmil/getBaseUrl.php
Last active March 6, 2019 06:28
Show Gist options
  • Save trungpv1601/2796b582e4c404274939f8a0f1af9463 to your computer and use it in GitHub Desktop.
Save trungpv1601/2796b582e4c404274939f8a0f1af9463 to your computer and use it in GitHub Desktop.
function getBaseUrl($includeTrailingSlash = FALSE)
{
$protocol = (isset($_SERVER['HTTPS']) && 'off' !== $_SERVER['HTTPS']) ? 'https' : 'http';
$domain = php_uname('n');
$port = '';
if (isset($_SERVER['HTTP_HOST'])) {
$domain = filter_input(
INPUT_SERVER,
'HTTP_HOST',
FILTER_SANITIZE_STRING,
FILTER_FLAG_NO_ENCODE_QUOTES
);
} elseif (isset($_SERVER['SERVER_NAME'])) {
$domain = filter_input(
INPUT_SERVER,
'SERVER_NAME',
FILTER_SANITIZE_STRING,
FILTER_FLAG_NO_ENCODE_QUOTES
);
}
if (FALSE === strpos($domain, ':')
&& (('http' === $protocol && 80 !== (int) $_SERVER['SERVER_PORT'])
|| ('https' === $protocol && 443 !== (int) $_SERVER['SERVER_PORT']))
) {
$port = ':' . (int) $_SERVER['SERVER_PORT'];
}
$pathInfo = pathinfo($_SERVER['PHP_SELF']);
$baseUrl = rtrim($pathInfo['dirname'], '/');
if($baseUrl) {
$basePath = basename(__DIR__);
$posPath = strpos($baseUrl, $basePath);
if($posPath){
$baseUrl = substr($baseUrl, 0, strlen($basePath) + 1);
} else {
$baseUrl = '';
}
}
$trailingSlash = $includeTrailingSlash ? '/' : '';
return "${protocol}://${domain}${port}${baseUrl}${trailingSlash}";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment