Skip to main content
Inspiring
November 5, 2018
Answered

Using root-relative paths for PHP includes...

  • November 5, 2018
  • 2 replies
  • 2700 views

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 has been closed for replies.
    Correct answer Paul-M

    Try this:

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

    2 replies

    Participant
    December 26, 2020

    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.  :-((  

    Paul-MCorrect answer
    Legend
    November 5, 2018

    Try this:

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

    Paul-M - Community Expert
    Under S.Author
    Inspiring
    November 5, 2018

    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!

    Legend
    November 7, 2018

    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

        }

    ?>

    Paul-M - Community Expert