Because header("Location: "); header needs to be used with absolute paths rather then relative ones, I made up this function to get a absolute path by using the $_SERVER variables.
function getAbsolutePath($relativePath = "/site/123/") {
if (isset($_SERVER['HTTPS'])) {
$protocol = 'https';
} else {
$protocol = 'http';
}
$host = $_SERVER['HTTP_HOST'];
$port = $_SERVER['SERVER_PORT'];
$absolutePath = 'Location: ' . $protocol . "://" . $host . ":" . $port . $relativepath;
return $absolutePath;
}
Is this the perfect method to do so, or are they any better alternatives?
That’s the “textbook” way of making an absolute URI.
A few caveats I would like to highlight.
$_SERVER['HTTPS']may not always be defined; the condition of$_SERVER['SERVER_PORT'] == 443should be inspected in that case; if you’re behind a HTTPS load balancer that forwards the traffic via HTTP and none of the aforementioned methods work, you may have to hard code it.$_SERVER['HTTP_HOST']is not always defined either; this happens rarely,HTTP/0.9didn’t define it and some home brew HTTP scripts may not pass it. You could look at$_SERVER['SERVER_NAME']to find an alternative.If the protocol and port is
http, 80orhttps, 443respectively, you don’t need to add:$port.