Open In App

How to get the Base URL with PHP ?

The term “Base URLrefers 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.

Example: This example shows the above-explained approach.




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

Output:

// If current URL is
https://www.geeksforgeeks.org/problem-of-the-day/
// Output:
https://www.geeksforgeeks.org/

Using parse_url()

The parse_url() is an in-built function that breaks down a URL into its components and returns an associative array. The base URL can be obtained using parse_url() function to extract the required components from the URL.

Example: This example shows the above-explained approach.




<?php
 
$parsed_url = parse_url($url);
$base_url = $parsed_url['scheme'] . "://" . $parsed_url['host'] . "/";
 
echo $base_url;
?>

Output
https://www.geeksforgeeks.org/

Article Tags :