简体   繁体   中英

Having issues with getting root path directory from different folders

I am trying to connect a certain header file for different files in different folders. The problem is when having the same file included in for example /backend it will be easily called directly (as the index is also in /backend) but when calling it from backend/pages it doesnt recall the link structure anymore resulting in a deadlink.

I have tried every possible thing with ../ and different header files but that is a no go. Trying to find a solution such as the url below comes really close but yet I cannot seem to figure it.

Root path variable in a PHP project

What would be the best way to include the root automatically in an include or require for example.

If you're using a front controller (like an index.php file) that is starting and executing your entire application you can just set a constant there like define('APP_ROOT', __DIR__); and that'll set the root to be your front controller.

You can access your header file from anywhere then by doing APP_ROOT . "/includes/header.php" APP_ROOT . "/includes/header.php"

If you are not using a front controller, then you can set this in each file. So for backend/pages it'd be something like ./../includes/header.php . or better still, use $_SERVER['DOCUMENT_ROOT'] to get the root of your application as provided by your web server vhosts config. (Apache of NGINX most likely)

$_SERVER['DOCUMENT_ROOT'] . "/app/backend/includes/header.php" $_SERVER['DOCUMENT_ROOT'] . "/app/backend/includes/header.php" for example.

What would be the best way to include the root automatically in an include or require for example.

I'm not aware of any method to do that without modifying PHP itself and re-compiling from source, but I could be wrong. Your root path will always be stored in $_SERVER['DOCUMENT_ROOT'] .

I think what you might want to look into is autoloading and more specifically PSR-4 and composer .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM