Tutorial :How to have included/required scripts use local files


My situation: I have a class that I want to use in a number of places, so I placed it high in the directory tree:


It uses a config file located in the same directory called config.ini and references it locally in the constructor. However, when I include it from a script in a different directory, it tries to load the config file from the directory the calling script is in. Is there any way I can look in the directory the included file is in? Ideally I could move the script to a different directory and not make any changes to it.


You should use the absolute path when including/loading files. And you can retrieve that absolute path with the __FILE__ constant and dirname function:


This will five you the absolute path of the config.ini file in the same directory the currently executed script file is located in. So when that code is executed in your classA.php script file, you would get /www/libs/classA/config.ini.


You should be able to include/require a file from the current file's directory if you have no path info in the argument, e.g. include('file2.php');. But I think even if you have './file2.php'), then it's going to become relative to the directory of the first-included/executed script.

I like the dirname(____FILE____)... method, but I believe in the case where a certain set of files is intended to always be deployed in the same directory, the direct file include promotes cohesion.

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »