Relative Include Files

I have a file

worker / activity / bulk_action.php, which includes the file

include('../../classes/aclass.php'); 

Inside aclass.php it does:

 include ('../tcpdf/config/lang/eng.php'); 

It seems that inclusion in the second file uses the working directory of the first files instead of referring to itself, which leads to an error. How it works?

+1
php
Mar 22 2018-11-22T00:
source share
3 answers

You can adapt the second include with:

 include (__DIR__.'/../tcpdf/config/lang/eng.php'); 

The magic constant __DIR__ refers to the current .php file and adds a relative path after that, will lead to the correct location.

But it only works with PHP5.3, and you will have to use the dirname(__FILE__) construct if you need compatibility with older settings.

+10
Mar 22 '11 at 10:13
source share

You would be better off setting the correct value in include_path and then use paths relative to this directory.

 set_include_path( get_include_path() . PATH_SEPARATOR . realpath(__DIR__ . '/your/lib') ); include 'tcpdf/config/lang/eng.php'; include 'classes/aclass.php'; 

I also suggest you take a look at startup . This will make the file obsolete.

+1
Mar 22 '11 at 10:15
source share

Files are included based on the specified file path or, if none are specified, the include_path is specified. If the file is not found in include_path, include () will finally check in the calling script its own directory and current working directory before the failure.

You can use dirname(__FILE__) to get the path to the directory where the current script is located:

 include(dirname(dirname(__FILE__)) . '/tcpdf/config/lang/eng.php'); 

(starting with PHP 5.3 you can use __DIR__ )

Or, define a constant in the first file that points to the root directory and use it in your included ones.

0
Mar 22 '11 at 10:15
source share



All Articles