Search code examples
phprequire-once

php require_once not working the way I want it to.. relative path issue


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


Solution

  • 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";