How to get the Base URL with PHP ?
Last Updated :
07 Mar, 2024
The term "Base URL" refers to the base or starting point for a set of related URLs. For example, if you have a website with multiple pages or an API with various endpoints, the Base URL is the common part shared by all those URLs. It typically includes the protocol (such as "http" or "https"), the domain name (e.g., "example.com"), and sometimes a path indicating a specific resource or context (e.g., "/api/v1").
Example:
// A Simple URL
url = https://www.example.com/one-two/two-three-four/
// Base URL of above mentioned URL
base-url = https://www.example.com
These are the following approaches:
Using $_SERVER super global
The $_SERVER is a super global variable in PHP that contains the details related to the header, paths, and script locations. The base URL can be constructed using information from the $_SERVER super global array, which provides server-related information.
- Using the $_SERVER[‘HTTPS’] in isset() function, will tell us if HTTPS is “on”, and if HTTPS is enabled then we have to use “https” in the URL, otherwise we use "http".
$_SERVER['HTTP_HOST'] contains the host header sent by the client.
Example: This example shows the above-explained approach.
PHP
<?php
$protocol = isset($_SERVER['HTTPS']) &&
$_SERVER['HTTPS'] === 'on' ? 'https://' : 'http://';
$base_url = $protocol . $_SERVER['HTTP_HOST'] . '/';
echo $base_url;
?>