Jump to content

Requires file using absolute path instead of relative


JustinK101

Recommended Posts

I have the following file requires/requires.php which basically links a whole bunch of other php class files.

 

require_once("classes/Database.php");
...

 

The problem is that I was trying to use relative paths to the requires files inside of requires.php. That inst going to work because the path from which requires.php is called will not always resolve to classes/Database.php. Sometimes it will be ../classes/Database.php other times ../../classes/Database.php, etc, depending on the location of the file that actually calls require_once("requires/require.php").

 

So long story short I though to use absolute paths in the require.php file:

 

require_once("/product/development-code/classes/Database.php");
...

 

As you can see that is ugly, also that path might change and I don't want to have to remember to manually update all the paths inside of requires.php. Is there a way I can set the ROOT directory for a project, so I can simply do:

 

// / acutally means /product/developent-code
require_once("/classes/Database.php");
...

 

Hopefully that makes sense, this is sort of hard to explain.

Got another problem, here is the structure:

 

/product/development-code/widgets/clock/clock.php

 

Is trying to require a file at:

 

/product/development-code/widgets/clock/javascript/clock.js

 

Here is the code I am usig:

 

require_once(dirname(dirname(dirname(__FILE__))) . "/widgets/clock/javascript/clock.js");

 

I don't get a php fatal eror about the require but looking at ySlow the javascript path it tries to import is all wrong, it is:

 

http://www.mydomain.com/home/timecard/public_html//product/development-code/widgets/clock/javascript/clock.js

 

I need /home/timecard/public_html/ stripped off.

 

__FILE__ returns the absolute path to the file where the line of code actually is (so the required file), not the orginating file (which is where the current working directory is)

 

the first dirname() strips off the filename from the return value of __FILE__, leaving you the directory in which __FILE__ is in.

 

the second dirname() strips another directory off. you could use just one dirname() and a ../ but i prefer the double dirname(). also, the number of dirname()s you use will depend on where you want to go to to get your included file.

 

lastly, if you are using php5+, look into autoloading for classes. you can use the same concept as above, but apply it generically and have classes load automatically: http://us.php.net/autoload

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.