3
votes

I have structured a server with this file and folders:

index.php
|lib -> lib.php
|framework -> fw.php
|folderA -> index2.php

In lib.php there is functionA() with a require_once inside that calls "fw.php" correctly from index2.php:

functionA(){
    require_once "../framework/fw.php";
    //other stuff... 
}

if it's called from index.php, the path must be changed. I really need a method to include paths dynamically without setting up a specific code inside every page.

Does exist a method to fix the path?

I tried to use __FILE__, dirname()...but without a satisfied solution.

2
Why not use an absolute path?nanofarad

2 Answers

3
votes

You might have to tweak this to get it to work depending on how your path is set up ... but for most standard setups this will work.

$basepath = substr($_SERVER['DOCUMENT_ROOT'], 0, strrpos($_SERVER['DOCUMENT_ROOT'], '/')). 
'/framework/';

require_once($basepath.'fw.php');
1
votes

If using php 5.3+ you can use the magic constant __DIR__

functionA(){
    require_once __DIR__."/../framework/fw.php";
    //other stuff... 
}

This will take the path of the functionA of lib/lib.php and go from there even if lib.php is included in index.php or anywhere.

And for previous PHP versions: dirname(__FILE__)