I'm trying to create a config.php file that defines a global variable which contains the path to a directory called "projectfiles". The idea is that any file can point to this directory regardless of where it is in the file tree.
Can I use __DIR__
for this? Would someone be willing to give me an example of how this might work? I was thinking of something like the following:
I want to define an directory here: in the /config.php
file
$projectfiles = __DIR__("projectfiles/")
Then I want a library file to be able to use this variable in /venders/library/generalfunctions.php
file
include("../../../config.php");
$file = $projectfiles/testfile.php
Suggestions?
It looks like the architecture of this application is less than optimal, but without knowing more, I can't comment on that..
I suggest defining it as a constant so that it can't be altered and is available no matter the scope.
Assuming:
/config.php
/projectfiles/include_me.php
Keep in mind that
__DIR__
will reference the directory thatconfig.php
is in. Ifconfig.php
is the parent folder ofprojectfiles
then the above will work.__DIR__
is certainly what you are looking for. Use it to provide relative paths for required files. I would highly suggest usingrequire_once
orinclude_once
for all library files.Using the first line ensures you wont run into trouble with PHP 5.2 and back. This will allow you to include files based on directory structure instead of relative to the script called. Many frameworks use
dirname(__FILE__)
instead, but it is rather wasteful to run more than once. It is better to just add it somewhere with a check.