Skip to main content
Inspiring
Nov 5, 2018 9:46 PM UTC
Answered

Using root-relative paths for PHP includes...

Hi,

I'm an average HTML programmer who knows just enough about PHP to use includes.

I have a simple website layout that uses PHP includes like this :

<?php include ('../_header.php'); ?>

<?php include ('content.php'); ?>
<?php include ('../_footer.php'); ?>

Can't use root-relative paths in includes because, as you pros already know, root-relative on the server means something completely different.

Is there a quick and easy way for me to remedy this, perhaps with an added line in either the header or htaccess file? The convenience of being able to move files outside of DW without having to worry about links like these is worth the initial bother, I find.

Thanks!

    This topic is closed to new replies. Start a new post to keep the conversation going.
    Paul-MCorrect answer
    Legend
    Nov 5, 2018 11:00 PM UTC

    Try this:

    include($_SERVER['DOCUMENT_ROOT'].'somefile.php')

    Paul-M - Community Expert

    4 replies

    Participant
    Dec 26, 2020 12:54 PM UTC

    SEVERE PROBLEM with this solution:  This file connection is not recognized anymore by DW. 
    So the included file will not appear as tab beside the source code tab anymore.  :-((  

    Translate
    Paul-MCorrect answer
    Legend
    Nov 5, 2018 11:00 PM UTC

    Try this:

    include($_SERVER['DOCUMENT_ROOT'].'somefile.php')

    Translate
    Paul-M - Community Expert
    Under S.Author
    Inspiring
    Nov 5, 2018 11:25 PM UTC

    Energize  wrote

    Try this:

    include($_SERVER['DOCUMENT_ROOT'].'somefile.php')

    You just changed my life.

    So I just repeat this everywhere I use a root-relative path?

    Works for me, thanks!

    Translate
    Legend
    Nov 7, 2018 4:26 PM UTC

    I don't know what your set up is, but yes is probably the short answer. If you need different output for your local testing server for example you might want to use if / else:

    <?php

    $dev = array('localhost', '127.0.0.1');

    //Check If local testing server before outputting stuff

    if(in_array($_SERVER['HTTP_HOST'], $dev))  {

            // DO SOMETHING IF LOCALHOST DETECTED

    }else {

            // DO SOMETHING ELSE IF NOT LOCALHOST

        }

    ?>

    Translate
    Paul-M - Community Expert