Here is a solution that works on both remote and local servers and does not require a domain name change:
$protocol = isset($_SERVER["HTTPS"]) ? 'https://' : 'http://'; $url_base = $protocol . $_SERVER['HTTP_HOST'];
With these 2 lines, you will not need to change the code if you change your domain name, and you will not need to change it if you switch between HTTP and HTTPS. Feel free to change the variable names as you wish.
So your link code will look something like this:
<a href="<?php echo $url_base; ?>/relative/path/to/document.html">link</a>
IMPORTANT SAFETY UPDATE:
However, there is a security risk with this solution. Here's an article about it .
The variables $_SERVER['HTTP_HOST'] and $_SERVER['SERVER_NAME'] can be changed by sending a different host header when accessing the site:
curl -H "Host: notyourdomain.com" http://yoursite.com/
So any URLs that used $_SERVER['HTTP_HOST'] or $_SERVER['SERVER_NAME'] use notyourdomain.com.
Taking this further, imagine that an attacker fills in the reset form password with your email and changes the host header. Password reset email will direct you to their site. If you paid attention to the domain, youre excellent, but normal users do not and thats why phishing attacks work.
Therefore, use it with caution or better avoid using it.
Here you can use several environments from the related article:
When working with multiple environments, you can use $_SERVER['HTTP_HOST'] and $_SERVER['SERVER_NAME'] , but only to check which domain you enter, and then manually set the correct URL. You can save it with a simple 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 this a little shorter:
$domains = array('domain.com', 'dev.domain.com', 'staging.domain.com', 'localhost'); $domain = in_array($_SERVER['HTTP_HOST'], $domains) ? $_SERVER['HTTP_HOST'] : 'localhost';