PHP脚本绝对路径

时间:2013-08-27 18:12:26

标签: php path

我有一个位于/fileupload/index.php中的脚本。我们叫A. 我希望在A中包含一个脚本。让它命名为B. B位于/includes/class/class.product.php

如何使用realpath(dirname( FILE ))在A中包含B?

如果A位于/index.php我像B一样包括......

require_once realpath(dirname(__FILE__)).'/includes/class/class.product.php';

但主要问题是A位于/fileupload/index.php。我该怎么办 ?我不想硬编码。这就是我要问的原因。

1 个答案:

答案 0 :(得分:0)

首先,你必须像这样定义SITE_ROOT

// PAGE_FILE = this is the path of the current file
// SITE_ROOT = this is the root of your site
if (DIRECTORY_SEPARATOR == '/') {
    //the site is hosted in linux server
    define('PAGE_FILE', __FILE__);
} else {
    //the site is hosted in Windows server, so some extra processing is necessary
    define('PAGE_FILE', str_replace(DIRECTORY_SEPARATOR, '/', __FILE__));
}
define('SITE_ROOT', substr(PAGE_FILE, 0, -(mb_strlen($_SERVER['PHP_SELF']))));

现在,只需编写下面的代码即可包含您的文件,无论它位于何处:

include SITE_ROOT . '/includes/class/class.product.php'
include SITE_ROOT . '/my-path/another-file.php'
include SITE_ROOT . '/file-in-root-directory.php'

我希望这会给你一个永久的解决方案。

相关问题