Skip to content
PHP Logo

How can the $_SERVER['HTTP_HOST'] variable be used to retrieve the base URL in PHP?

To retrieve the base URL in PHP using the $_SERVER['HTTP_HOST'] variable, you can concatenate it with the current protocol (http or https) and the document root. This will give you the complete base URL of the website.

php
$base_url = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://" . $_SERVER['HTTP_HOST'] . $_SERVER['DOCUMENT_ROOT'];
echo $base_url;