Search code examples
phpdirectorypathnestedrelative-path

PHP broken relative links in nested directories


I'm sure I'm missing some simple explanation, but I want to confirm - so assume I know very little.

I have a directory structure like so (for the time being) of:

My main site (localhost/project/ on my testing server, and C:/xampp/htdocs/project on my HDD) with these files and folders:

Root
  graphics
    variousgraphics.png

  support
    stylesheet.css


  templates
    header.php
    footer.php
    initialize.php

  you
    default.php

  index.php
  anotherfile.php

Up until I created the folder 'you' everything was fine, i.e. I included the initialize file for index.php as <?php include(templates/initialize.php) ?>

But when I decide to include initialize.php using the above method for the default.php file (inside 'you'), it errored out with Warning: include(templates/initialize.php) [function.include]: failed to open stream: No such file or directory in C:\xampp\htdocs\photoquilt\you\default.php

So naturally I appended ../ to create <?php include(../templates/initialize.php) ?> but then of course that didn't work because the files referenced inside initialize.php weren't appended in the same way, and so I get to here.

It's worth noting for me, an echo of $_SERVER['document_root'] leads to C:/xampp/htdocs

So in summary:

Is there any way to make sure all the link/paths work correctly irrespective of where the originating path was from?


Solution

  • In default.php you can define a constant like

    define('ROOT_PATH', dirname(__DIR__));
    

    or for php versions prior to 5.3.0

    define('ROOT_PATH', dirname(dirname(__FILE__)));
    

    and then use ROOT_PATH in all scripts to build the the file paths.

    see
    - http://docs.php.net/language.constants.predefined
    - http://docs.php.net/dirname