Sieu Phan Sieu Phan - 7 months ago 27
PHP Question

PHP how to get the base domain/url?

function url(){
if(isset($_SERVER['HTTPS'])){
$protocol = ($_SERVER['HTTPS'] && $_SERVER['HTTPS'] != "off") ? "https" : "http";
}
else{
$protocol = 'http';
}
return $protocol . "://" . $_SERVER['HTTP_HOST'];
}


For example with the function above, it works fine if I work with the same directory, but if I make a sub directory, and work in it, it will give me the location of the sub directory also for example. I just want
example.com
but it gives me
example.com/sub
if I'm working in the folder
sub
. If I'm using the main directory,the function works fine. Is there an alternative to
$_SERVER['HTTP_HOST']
?

Or how could I fix my function/code to get the main url only? Thanks.

Answer

Use SERVER_NAME.

echo $_SERVER['SERVER_NAME']; //Outputs www.example.com
Comments