views:

521

answers:

2

I'm having problems assigning a relative path to require_once. I'm sure it's something simple that I'm not seeing...

folder directory structure level 1: site level 2: include level 2: class

so... site/include/global.php <-- this is where function autoload is being called from site/class/db.php

when I attempt to use

function__autoload($className)
{
     require_once '../class/'.$className.'.php';

}

i get:

Warning: require_once(../class/db.php) [function.require-once]: failed to open stream: No such file or directory

Fatal error: require_once() [function.require]: Failed opening required '../class/db.php' (include_path='.;./includes;./pear')

What am I doing wrong? It'll work fine if I plop the global.php in the class folder so I'm assuming it's my poor understanding of relative paths that is causing the problem..

Thanks

A: 

Does this work (apache only, i believe)

require_once($_SERVER['DOCUMENT_ROOT'] . '/class/' . $classname '.php');
Andrew Backer
I don't want to use document root because I'm working off the site remotely. I have two versions of the site, the main site and my test version and the site folder is named differently from the test version. Absolute paths will not work if I want to have both the test and main working correctly.. : /
payling
Oh. Not separate ports, just /test and /main. That means that your dev env isn't a mirror of how you will deploy, but I know the temptation.
Andrew Backer
+3  A: 

require(_once) and include(_once) work relative to the path of the first script, i.e. the script that was actually called.

If you need to require something in an included or required file, and would like to work relative to that file, use

dirname(__FILE__)."/path/to/file";

or as @Arkh points out, from PHP 5.3 upwards

__DIR__."/path/to/file";
Pekka
Too fast:(. You can also use `__DIR__` with php5.3+
Arkh
Cheers @Arkh, updated my answer.
Pekka
thanks mate.require_once dirname(__FILE__).'/../class/'.$className .'.php';works perfectly!I didn't know that require starts at the root directory by default. I assumed (you should never assume) that it was from current directory.Anyways, Thanks Pekka.
payling
@payling You're welcome. One important distinction, by "root" I mean the script that was called in the browser, not necessarily the root directory. My choice of words was a bit misleading, sorry. I've edited it a bit.
Pekka
Gotcha. the home page (that calls autoload function) is located in site directory. The global.php page is in my include directory but since I included the global.php inside home page it's techinically in the site directory for the moment. 'class/'.$className.'.php'; works, but it's probably best to use the first solution we came up with using the dirname because I could be including script form a location other than the site directory so 'class/' will not always work! Thanks again!
payling
Exactly. Perfectly put! Cheers.
Pekka