Get Current Domain

Get Current Domain

I have my site on the server .

On this server I have two domains:

one.com and two.com

I would like to get the current domain using PHP, but if I use $_SERVER['HTTP_HOST'] then it is showing me

myserver.uk.com

instead of:

one.com or two.com

How can I get the domain, and not the server name?

7

8 Answers

Try using this:

$_SERVER['SERVER_NAME']

Or parse:

$_SERVER['REQUEST_URI']

Reference: apache_request_headers()

4

The best use would be

echo $_SERVER['HTTP_HOST'];

And it can be used like this:

if (strpos($_SERVER['HTTP_HOST'], 'banana.com') !== false) {
    echo "Yes this is indeed the banana.com domain";
}

This code below is a good way to see all the variables in $_SERVER in a structured HTML output with your keywords highlighted that halts directly after execution. Since I do sometimes forget which one to use myself - I think this can be nifty.

<?php
    // Change banana.com to the domain you were looking for..
    $wordToHighlight = "banana.com";
    $serverVarHighlighted = str_replace( $wordToHighlight, '<span style=\'background-color:#883399; color: #FFFFFF;\'>'. $wordToHighlight .'</span>',  $_SERVER );
    echo "<pre>";
    print_r($serverVarHighlighted);
    echo "</pre>";
    exit();
?>
0

The only secure way of doing this

The only guaranteed secure method of retrieving the current domain is to store it in a secure location yourself.

Most frameworks take care of storing the domain for you, so you will want to consult the documentation for your particular framework. If you're not using a framework, consider storing the domain in one of the following places:

   Secure methods of storing the domain      Used By
A configuration file   Joomla, Drupal/Symfony
The database   WordPress
An environmental variable Laravel  
A service registry   Kubernetes DNS
Sophia Al-Mansoor
Author

Sophia Al-Mansoor

Sophia analyzes international trade, startup ecosystems, retail transformation, and supply chain logistics for modern digital publications.