Here is a solution that works both on remote and local servers and doesn't require to change the domain name:
$protocol = isset($_SERVER["HTTPS"]) ? 'https://' : 'http://';
$url_base = $protocol . $_SERVER['HTTP_HOST'];
With these 2 lines you won't need to change the code if you change your domain name and also you won't need to change it if you switch between HTTP and HTTPS. Feel free to change variable names as you prefer.
So then your code for links would look something like this:
<a href="<?php echo $url_base; ?>/relative/path/to/document.html">link</a>
IMPORTANT UPDATE REGARDING SECURITY:
There is however a security risk with this solution. Here's an article on it.
The $_SERVER['HTTP_HOST']
and $_SERVER['SERVER_NAME']
variables can be
changed by sending a different Host header when accessing the site:
curl -H "Host: notyourdomain.com" http://yoursite.com/
Doing that, any URLs that used $_SERVER['HTTP_HOST']
or $_SERVER['SERVER_NAME']
would
use notyourdomain.com.
Taking this further, imagine an attacker fills out a password reset
form with your email and changes the Host header. The password reset
email would then direct you to their site. If you’re paying attention
to the domain, you’re fine, but normal users don’t and that’s why
phishing attacks work.
So use it with caution or better avoid using it.
Here's a way to deal with multiple environments from the linked article:
When dealing with multiple environments, you can use
$_SERVER['HTTP_HOST']
and $_SERVER['SERVER_NAME']
, but only to check
which domain you’re on and then manually set the correct URL. You
could keep it simple with an array of valid domains:
$domains = array('domain.com', 'dev.domain.com', 'staging.domain.com', 'localhost');
if (in_array($_SERVER['HTTP_HOST'], $domains)) {
$domain = $_SERVER['HTTP_HOST'];
}else {
$domain = 'localhost';
}
You can also make it a bit shorter:
$domains = array('domain.com', 'dev.domain.com', 'staging.domain.com', 'localhost');
$domain = in_array($_SERVER['HTTP_HOST'], $domains) ? $_SERVER['HTTP_HOST'] : 'localhost';