A way to dynamically include paths in php?

I created a server with this file and folders:

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

      

Lib.php has an A () function with require_once inside that calls fw.php from index2.php correctly:

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 dynamically include paths without setting up specific code on each page.

Is there a method to fix the path?

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

+3


source to share


2 answers


You may have to tweak it to get it to work depending on how your path is configured ... but for most standard settings, this will work.



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

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

      

+3


source


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

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

      



This will follow the path of function A from lib/lib.php

and go from there, even if lib.php is included in index.php or wherever.

And for previous PHP versions: dirname(__FILE__)

+1


source







All Articles