-1

I am having a tough time with setting the include property per page.

It seems that it works fine when everything is in the same directory but if i reference a page from another directory then everything stops working, as it probably should.

Now whats the best way to reference classes and files from different directories in php? There must have been someone who have figured out the trick to reference a file from a different folder.

Currently, i am doing it as per the following

include ("../config/Authenticate.php");

Now Authenticate.php may reference another class or include another code. So how do you make it all work together?

Nilesh Tailor
  • 146
  • 2
  • 6

4 Answers4

0

You can put this at the top of your index page, obviously change the paths to ones relevant to your application. Then simply include('some_file.php'), from any location that is in the include paths set.

$publicPath = getcwd();
chdir(__DIR__ . "/..");
$sitePath = getcwd();
chdir($publicPath);

$paths = array(
    $sitePath . '/config',
    $sitePath . '/config/foo',
    $sitePath . '/foo',
    $sitePath . '/foo/bar',
    get_include_path()
);

set_include_path(implode(PATH_SEPARATOR, $paths));
unset($paths);

Edit* This assumes you have a public folder with index.php inside and all of your other files outside of the public folder.

MonsterTKE
  • 3
  • 1
  • 4
0

You can use __DIR__ in your include path to set the path relative to the file.

You include would become:

include (__DIR__ . "/../config/Authenticate.php");
Schleis
  • 41,516
  • 7
  • 68
  • 87
0

If the file you're including needs to include another file, as long as you have the inclusion script within that file also, it should work.

mavili
  • 3,385
  • 4
  • 30
  • 46
0

Here is an approach that worked out for me.

$arr_path = explode(DIRECTORY_SEPARATOR, __DIR__);

$arr_path = array_reverse($arr_path);
$depthCounter=0;
for($i=0;$i<count($arr_path);$i++){
    // just replace BDW with your main directory
    if ($arr_path[$i] === "BDW"){
        $depthCounter = $i;
    }   
}
// clear array
unset($arr_path);

$DEPTH = "";
for($i=0;$i<$depthCounter;$i++){
    $DEPTH= $DEPTH . "../";
}


include ($DEPTH . 'config/SessionStart.php');

It's not the cleanest code. But it seems to work. Integrating this @MonsterTKE's approach would probably work for most people.

Nilesh Tailor
  • 146
  • 2
  • 6