| 表達式 | 含義 | 示例輸出 (文件:D:/phpweb/example/include_path.php) |
|---|---|---|
__FILE__ | 當前文件絕對路徑 (符號鏈接已解析) | D:/phpweb/example/include_path.php |
__DIR__ | 當前文件所在目錄 (PHP 5.3+) | D:/phpweb/example |
dirname(__FILE__) | 兼容寫法,等同 __DIR__ | D:/phpweb/example |
$_SERVER['SCRIPT_FILENAME'] | 入口腳本絕對路徑 (非 include 文件) | D:/phpweb/example/index.php |
$_SERVER['DOCUMENT_ROOT'] | Web 服務器文檔根目錄 | D:/phpweb |
getcwd() | 當前工作目錄 (CLI 為執行目錄,Web 為入口腳本目錄) | D:/phpweb/example |
當 include/require 參數為**相對路徑且不以 ./、../ 開頭**時 (如 include("config.php")),PHP 會按順序搜索:
include_path 指定的目錄列表 (以 PATH_SEPARATOR 分隔,Windows ;、Linux :)__DIR__)getcwd())因此 include("./config.php") 比 include("config.php") 快:前者直接定位,後者需遍歷 include_path。
// 1. ini_set (所有版本)
ini_set('include_path', '/usr/lib/pear');
// 2. set_include_path (PHP 4.3.0+)
set_include_path('/usr/lib/pear');
// 3. 在原有基礎上追加 (推薦)
$newPath = '/usr/lib/pear';
set_include_path(get_include_path() . PATH_SEPARATOR . $newPath);
// 結果類似:.:/usr/share/php:/usr/lib/pear
// public/index.php (入口文件)
define('APP_ROOT', __DIR__ . '/../');
set_include_path(
APP_ROOT . 'library' . PATH_SEPARATOR .
APP_ROOT . 'vendor' . PATH_SEPARATOR .
get_include_path()
);
vendor/autoload.php 註冊了 PSR-4 自動加載,**無需**手動修改 include_path。直接 use Vendor\Package\Class 即可。
set_include_path 會影響後續所有 include/require,且不執行緒安全 (PHP-FPM worker 間隔離)。**僅在啟動階段設置一次**。
/**
* 獲取專案根目錄 (根據入口腳本推導)
*/
function get_project_root() {
return dirname($_SERVER['SCRIPT_FILENAME']);
}
/**
* 安全拼接路徑 (防止目錄遍歷)
*/
function safe_join($base, $relative) {
$base = rtrim(realpath($base), DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR;
$full = realpath($base . $relative);
if ($full === false || strpos($full, $base) !== 0) {
throw new InvalidArgumentException("路徑遍歷攻擊: $relative");
}
return $full;
}
/ 作為分隔符 (Windows 含)。DIRECTORY_SEPARATOR 或 escapeshellarg()。realpath() 可統一解析為系統原生絕對路徑。__DIR__、__FILE__ 獲取當前文件路徑。$_SERVER['SCRIPT_FILENAME'] 定位專案根目錄。include_path 僅在啟動階段配置一次,業務代碼**禁止**動態修改。./ 前綴**,避免遍歷 include_path 開銷。include。