Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A way to include paths dynamically in php?

Tags:

path

php

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.

like image 576
Rox Avatar asked Jan 02 '26 06:01

Rox


2 Answers

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');
like image 155
Tech Savant Avatar answered Jan 03 '26 19:01

Tech Savant


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__)

like image 34
Onimusha Avatar answered Jan 03 '26 19:01

Onimusha



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!