Skip to content

Instantly share code, notes, and snippets.

@nmcgann
Last active March 14, 2017 21:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nmcgann/53d46d5af49a6f9976e50a0d1d00beb4 to your computer and use it in GitHub Desktop.
Save nmcgann/53d46d5af49a6f9976e50a0d1d00beb4 to your computer and use it in GitHub Desktop.
PHP function to automatically get a host url from $_SERVER variables to enable creation of absolute links etc. (Apache)
<?php
//e.g.semi-colon separated define list of all allowable hosts (does not need to show sub-domains - works automatically)
//$valid_hosts = 'first-host.com;second-host.com';
//create absolute url for page address - quite tricky to make this work on linux / windows and shared hosting and also
//php built-in web server.
//Constructed URL ends up in a trailing slash with the $target parameter appended.
//defaults to not checking a valid host list unless one is supplied
function get_host_url($target = '', $valid_hosts = '*'){
// Get HTTP/HTTPS (the possible values for this vary from server to server)
//$scheme = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] && !in_array(strtolower($_SERVER['HTTPS']),array('off','no'))) ? 'https' : 'http';
//handle forwarded load-balancer cases too
$isSecure = false;
if (isset($_SERVER['HTTPS']) && (strtolower($_SERVER['HTTPS']) == 'on' || $_SERVER['HTTPS'] == '1')) {
$isSecure = true;
}elseif(!empty($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https' ||
!empty($_SERVER['HTTP_X_FORWARDED_SSL']) && $_SERVER['HTTP_X_FORWARDED_SSL'] == 'on') {
$isSecure = true;
}
$scheme = $isSecure ? 'https' : 'http';
if (!in_array(intval(isset($_SERVER['SERVER_PORT']) ? $_SERVER['SERVER_PORT'] : 80), [80, 443])) {
$port = ":".intval($_SERVER['SERVER_PORT']);
} else {
$port = '';
}
$valid_hosts = preg_split('/;/',$valid_hosts, -1, PREG_SPLIT_NO_EMPTY);
$host = "";
foreach($valid_hosts as $h){
if($h === '*' || preg_match('#'.preg_quote($h,'#').'(|:\d+)$#', $_SERVER['HTTP_HOST'])){
$host = filter_var($_SERVER['HTTP_HOST'], FILTER_SANITIZE_URL); //can't use filter_input dur to fastcgi bug
$host = preg_replace('#:\d+$#','', $host); //remove port
break;
}
}
//ensure trailing slash and handle windows "\" oddities
$path = rtrim(strtr(dirname(filter_var($_SERVER['PHP_SELF'], FILTER_SANITIZE_URL)),'\\','/'),'/').'/';
return $scheme . "://" . $host . $port . $path . $target;
}
/* end */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment