在网站内引用页面的更好方法

Better way to refence pages within website

我为我的网站使用了一个复杂的文件夹结构,这使得组织我的内容变得简单。然而,当我需要 link 到一个页面时,我经常不得不采用这种方法:

include_once '../../../assets/php/DB/DBConnect.php';

有没有办法让我摆脱所有 ../ 的东西?

变化自

include_once '../../../assets/php/DB/DBConnect.php';

include_once $_SERVER["DOCUMENT_ROOT"].'/assets/php/DB/DBConnect.php';

注意 assets 应该是您的第一个子文件夹。

尝试

方法01

$path = $_SERVER['DOCUMENT_ROOT'];
$path .= "/assets/php/DB/DBConnect.php";
include_once($path);

方法02

include_once $_SERVER["DOCUMENT_ROOT"].'/assets/php/DB/DBConnect.php';

Note

I have found that in some environments DOCUMENT_ROOT does not seem to be properly set. I have devised a way that is independent of the server, and whether the hosting provider provides the ability to set an include or auto-prepend path as well.

Each directory contains a 'meta' file called '__php__.php' (or whatever one wants to call it). For any files in that directory, they simply include it as <?php include('__php__.php'); ?>. The file itself simply includes the one in the parent directory all the way up to the site root. The file in the site root then can include other files, a simply way of auto-including files even if a service provider does not support it, and also define a variable such as 'SITE_ROOTDIR', which can then be used later. If the document files are moved to another directory, they will still include the __php__.php file in that directory and still get the SITE_ROOTDIR constant from the top __php__.php file.

I also do something similar for a simple navigation bar, where each directory has a __navbar__.php file, and each page simply includes it at the correct location and it can include parent navigation elements and define its own navigation elements.

One advantage of this is that a part of the site can be sectioned in a sub-directory, and still get the root of that part, even if it isn't the actual document root. A disadvantage is that it may slow down while doing all the includes on a site with heavy traffic.

Yet another:

<?php set_include_path( get_include_path() . PATH_SEPARATOR . $_SERVER['DOCUMENT_ROOT'] ); ?>