Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nested php includes using './'

Tags:

php

I have several PHP files include()ing other files from several other directories.

In one of those included files: foo/bar.php, I want bar.php to include 3 other files contained in the directory foo. However bar.php is actually included by another file in another directory, which is included by yet another file, and so on.

If I did:

include('./apple.php');
include('./orange.php');

In foo/bar.php, will it include the correct files from the foo directory regardless of which file included bar.php in itself?

like image 485
Ali Avatar asked Aug 05 '26 16:08

Ali


2 Answers

Use the following instead:

include(dirname(__FILE__).'/apple.php');

I don't know if what you've posted will work reliably or not, but this will.

like image 128
Matthew Scharley Avatar answered Aug 08 '26 11:08

Matthew Scharley


No. Using ./ at the start of your include file name forces it to be searched from the "current directory" as set by your web server (most probably the directory of the initial script, or the DocumentRoot, depending on the webserver).

The way to get the behaviour you want depends on the value of your include_path (which can be modified with set_include_path() if necessary).

From the documentation for include():

Files for including are first looked for in each include_path entry relative to the current working directory, and then in the directory of current script. E.g. if your include_path is libraries, current working directory is /www/, you included include/a.php and there is include "b.php" in that file, b.php is first looked in /www/libraries/ and then in /www/include/. If filename begins with ./ or ../, it is looked for only in the current working directory or parent of the current working directory, respectively.

So, if there's no chance that the filename will be found in another directory in the include_path first, you could use include('apple.php').

If there is a possibility that apple.php exists elsewhere, and you want the copy in this folder to be used first, you could either use Matthew's suggestion, and

include(dirname(__FILE__).'/apple.php');

or, if you have many files to include from the current directory:

old_include_path = set_include_path(dirname(__FILE__));
include('apple.php');
include('orange.php');
include('peach.php');
include('pear.php');
set_include_path(old_include_path);
like image 24
Stobor Avatar answered Aug 08 '26 12:08

Stobor



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!