How to get the base url in php

Suppose you have to retrieve the URL of the application in PHP i.e http://example.com
Using this piece of code
1
2
3
4
5
6
//output : example.com
$DOMAIN = $_SERVER['SERVER_NAME'];
// output: http://
$protocol = stripos($_SERVER['SERVER_PROTOCOL'],'https') === true ? 'https://' : 'http://';
// output : http://example.com
$main_url = $protocol.$DOMAIN;
When you are running the application in the subfolder / subdomain in the main website.I.e http://example.com/myproject/
In this case you want to retrieve the base url of the application not the main site url.

Use this simple function to get the base url of your application.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
function getBaseUrl()
{
    // output: /myproject/index.php
    $currentPath = $_SERVER['PHP_SELF'];
 
    // output: Array ( [dirname] => /myproject [basename] => index.php [extension] => php [filename] => index )
    $pathInfo = pathinfo($currentPath);
 
    // output: example.com
    $hostName = $_SERVER['HTTP_HOST'];
 
    // output: http://
    $protocol = strtolower(substr($_SERVER["SERVER_PROTOCOL"],0,5))=='https://'?'https://':'http://';
 
    return $protocol.$hostName.$pathInfo['dirname']."/";
}
 
$base_url = getBaseUrl();

* If you like this post please don’t forget to subscribe Techies Badi - programming blog for more useful stuff

Related Posts