views:

463

answers:

2

I'm having issues with includes when the included file itself includes another file but refers to it with the dot prefix. For example there are three files - inc1.php, inc2.php, and subdir/test.php, the contents of which are -

subdir/test.php:

set_include_path(get_include_path().":../:../.");
require("inc1.php");

inc1.php:

require("./inc2.php");

inc2.php

echo "OK";

This include tree shown here fails with a failed to open stream: No such file or directory error. It works if inc1.php contains a simple require("inc2.php");, without the "./" prefix. I added "../." to the include path as an attempt to get it to work, but that had no effect.

Other than performing the include with the "./" prefix, what is the solution here, assuming that inc1.php and inc2.php are not writable and you can only alter subdir/test.php? How can you still include inc1.php from within test.php?

For reference, I'm using PHP 5.2.9.

+6  A: 

Always include using the following style, unless you have a (very) compelling reason not to:

inclue(dirname(__FILE__)."/inc2.php");

It saves all manner of headaches.

Matthew Scharley
... and in PHP 5.3 there is also a magic constant named `__DIR__` which is the same as `dirname(__FILE__)`.
Ignas R
I know people still running PHP4, so I prefer not to use the latest and greatest constants for the sake of backwards compatibility, but you are right.
Matthew Scharley
I am trying to use this with various scripts, e.g. Wordpress, which do not always follow that convention. Therefore the assumption taht inc1.php and inc2.php *cannot* be altered :) I need a solution that only edits test.php.
Tristan
If Wordpress uses the calling style shown above in it's core, then someone needs to be shot. If it's in a plugin/theme, then *"cannot be altered"* is probably more than a little strong.
Matthew Scharley
Yes, that's the include style Wordpress uses in it's index.php, and possibly other locations. There's also other popular scripts I've seen that use this in their core as well.
Tristan
A: 

A simple chdir() appears to work for this; changing test.php to:

chdir("../");
require("inc1.php");

It seems that "./" in inc1.php is interpreted as 'subdir/', so it looks for inc1.php only in the 'subdir' folder despite the include path.

Tristan