我有同样的问题,我在网上搜索了很多问题,但我没有找到任何问题,所以我自己做了,所以这里是:
define('GLOBAL_APP_ROOT', $_SERVER["DOCUMENT_ROOT"]); // you can append to this path the folder in which your site is deployed, in case you are working for a new version or something, and when you will deploy it you just delete it
public static function ToAbsolute($path)
{
$root = GLOBAL_APP_ROOT;
$cwd = getcwd(); // the current working directory => usually the directory from where the script its being called.
$cwd = str_replace('\\', '/', $cwd); // sometimes the current working directory is exposed with '\' instead of '/' - this usually happens on localhost
$path = ltrim($path,'/'); // cleans the left slash if exists => to avoid any writing errors/bugs
$depthPath = str_replace($root, '', $cwd); // gets the depth path of the current file
$depth = substr_count($depthPath, "/"); // gets the dept of the current working directory relative to document root
$relativePrefix = ""; // declaration of the relative prefix path
for($i = 0; $i < $depth; $i++) // building up the relative prefix
{
$relativePrefix = $relativePrefix."../"; // iterating the depth results in going back one folder
}
$relativePath = $relativePrefix.$path; // prepend the relative prefix to the absolute file path resulting in the relative path
return $relativePath;
}
我把这个函数放在root
了应用程序的url.php
文件中。当您想使用它时,它将是这样的:
<?php
require_once('url.php');
require_once(ToAbsolute('[file_path]'));
?>
因此,始终url.php
在您想使用它的任何地方包含第一个,并且始终include
将它与它的relative path
. include
您只需要使用该函数并传入的absolute path
所有其他文件file
笔记:
例如,如果您具有以下结构:
[root]
[admin]
[index.php]
[url.php]
[css]
[site.css]
在里面index.php
你必须有这样的东西来包括site.css
:
<?php
require_once('../url.php');
require_once(ToAbsolute('site.css'));
?>