Search code examples
phphyperlinksubdirectory

PHP/Proper use of includes in subdirectory


I have a sitewide include file that I include in pages in the main directory. However, I have put a bunch of pages with a common theme in a subdirectory. These pages need to reference the same include file. I am now running into problems with relative links in the include file for things like images since they call different paths depending on whether the main file is in the main directory or a sub-directory. For example, the link "images/pic.jpg" will work if the include is called from the main directory but will try to go to "sub/images/pic.jpg" if the include is called from the sub-directory.

I had solved this by using hard links that go back to the root as in /images/pic.jpg. However, I'd rather not use hard links as they may break if the site is moved to another directory etc.

Do all your pages calling a given include have to be in the same directory? Or is there some technique to get relative links in the include to work, even if the include is called from a sub-directory?

Many thanks.


Solution

  • There are no hard and fast rules - you can deal with your includes as you want, but you should endeavour to be consistent.

    The largest site I managed had thousands of include files scattered through hundreds of subdirectories. We used absolute paths throughout, using one variable to denote the root directory, and then concatenating the rest of the path on as required. When we needed to move the files, we needed to change that one variable, and the whole site moved.

    You can use relative links, but I found them a lot more confusing when you're trying to figure out what files are being called from where.