Home » PHP11 October 2010

PHP: How to get Main or Base URL?

Suppose you are on a page : http://example.com/category/php/
Now, the base URL or the main URL for the above link is : http://example.com

Similarly, in the case of local machine (localhost),
Suppose you are in the page : http://localhost/myproject/index.php?id=8
Here, the base or main URL is : http://localhost/myproject

Below is the code to get main or base URL from any URL link or path:-

Hope this helps. Thanks.


Get New Post by Email

Find me on

FacebookTwitterGoogle+LinkedInRSS Feed
  • Sirbelmonth

    Hi Mukesh!
    This base url works in localhost?
    Excellent blog, always helping me in magento! Thanks

  • Tcannon00

    Thanks for this! Clean, simple, and accounts for different protocols!

  • Paul Dinh

    tks for the post! :)

  • Ammar
  • picios

    a little correction for Windows
    rtrim($pathInfo[‘dirname’], ‘ /’)

  • Sema

    It worked perfectly :)

  • bh


  • worked perfectly, Thanks from Pakistan

  • thanks!! the substr result is ‘HTTP/’ then $protocol always will be ‘http://’