Open In App

How to get the Base URL with PHP ?

Last Updated : 07 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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.

  • 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;
?>


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.

  • The parse_url( ) function is applied to the given $url.
  • The base URL is constructed using the ‘scheme‘ (http or https) and ‘host‘ components obtained from the parsed URL.

Example: This example shows the above-explained approach.

PHP




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


Output

https://www.geeksforgeeks.org/


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads