Search code examples
phphtmlhyperlinkhrefprefix

How to use php to determine the site root inside href


I would like to be able to determine the root of my website using php, so I can switch between relative and absolute links for local and online testing with ease.

e.g. instead of changing href="/css/style.css" to href="http://example.com/css/style.css"

Could I use php to call in the site root?

Edit: Originally tried this with Sass & Css, but seemed like the wrong way of going about it.


Solution

  • You can easily achieve this using a scripting language such as PHP.

    At the top of your html page

    <?PHP
        $pageRoot = "http://localhost:8080"; // for example
        // $pageRoot = "http://myUrl.com"; // commented out as we're local testing first
    ?>
    

    Then to call your css files change the href to:

    href="<?=$pageRoot?>"/css/style.css"
    

    Then simply comment out the local host and un-comment the proper url when on your remote server