treehouse : what would you like to learn today?
Web Design Web Development iOS Development

how to php include with absolute path

  • So normally all my includes look like this or some variation... <?php include("../inc/plane.php"); ?>

    If I use a absolute path like this... <?php include("/inc/plane.php"); ?> it will not work and throw an error.

    I now there is a way by specify the root or something within the include or above it so I CAN USE an absolute path within my include? Can someone please show me? Thanks!

  • Thanks for pointing me in the correct direction. Looks like you can even do it easier with this bit...

    <?php include $_SERVER['DOCUMENT_ROOT'].'/inc/file.php'; ?>
  • Yep! That's how I roll with includes, works a treat! You can still do usual paths beginning with / for CSS/JS but PHP/Apache use the full document root, rather than relevant to the URL.

    So for example if you had your stylesheet linked as '/css/styles.css' - this would work fine as it's going "http://domain.com/css/styles.css".

    However, because PHP can see the whole route, your path is actually the file/folder path of the server. So "/css/styles.php" would go all the way back to the OS structure, for example if your site was at "/var/www/sitex/live_site/index.php" it would go back to before /var looking for that file.

    So $_SERVER['DOCUMENT_ROOT'] tells PHP to look in /var/www/sitex/live_site/ and thusly finds your file!

    It took me forever to work that out when I first started messing around with PHP includes!