简体   繁体   English

从不同文件夹获取根路径目录时遇到问题

[英]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. 问题是,例如在/ backend中包含相同文件时,将很容易直接调用它(因为索引也在/ backend中),但是从backend / pages调用它时,它不再调用链接结构,从而导致死链接。

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. 试图找到下面的URL这样的解决方案确实很接近,但是我似乎无法弄清楚。

Root path variable in a PHP project PHP项目中的根路径变量

What would be the best way to include the root automatically in an include or require for example. 例如,将根自动自动包含在include或require中的最佳方法是什么。

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__); 如果使用的前端控制器(如index.php文件)正在启动并执行整个应用程序,则可以在其中设置一个常量,例如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"从任何地方访问头文件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 . 因此,对于后端/页面,它将类似于./../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. $_SERVER['DOCUMENT_ROOT']是,使用$_SERVER['DOCUMENT_ROOT']获取Web服务器vhosts配置所提供的应用程序的根目录。 (Apache of NGINX most likely) (NGINX的Apache最有可能)

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

What would be the best way to include the root automatically in an include or require for example. 例如,将根自动自动包含在include或require中的最佳方法是什么。

I'm not aware of any method to do that without modifying PHP itself and re-compiling from source, but I could be wrong. 我不知道有任何方法可以做到这一点,而无需修改PHP本身并从源代码重新编译,但是我可能是错的。 Your root path will always be stored in $_SERVER['DOCUMENT_ROOT'] . 您的根路径将始终存储在$_SERVER['DOCUMENT_ROOT']

I think what you might want to look into is autoloading and more specifically PSR-4 and composer . 我认为您可能想研究的是自动加载功能 ,更具体地说是PSR-4composer

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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