Tristan
Tristan

Reputation: 1685

PHP include paths - include fails if file referred to with "./" prefix

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.

Upvotes: 1

Views: 2842

Answers (2)

Matthew Scharley
Matthew Scharley

Reputation: 132274

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

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

It saves all manner of headaches.

Upvotes: 7

Tristan
Tristan

Reputation: 1685

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.

Upvotes: 0

Related Questions