realpath()函數的基本語法如下:
string realpath(string $path)
$path :要解析的路徑。
返回值:成功時返回規範化的絕對路徑;失敗時返回false 。
以下是一個獲取當前目錄下某個文件夾的絕對路徑的基本示例:
$relativePath = 'uploads/images';
$absolutePath = realpath($relativePath);
if ($absolutePath !== false) {
echo "絕對路徑是: $absolutePath";
} else {
echo "路徑不存在或無法解析。";
}
realpath()只能解析實際存在的路徑。如果你傳入的路徑在文件系統中不存在,該函數將返回false 。因此在使用時,建議先判斷路徑是否存在:
if (file_exists($relativePath)) {
$real = realpath($relativePath);
echo $real;
} else {
echo "路徑不存在";
}
realpath()會解析符號鏈接,並將路徑中如..和.之類的符號消除。例如:
$path = '../project/./uploads/../logs';
echo realpath($path);
該調用將返回project/logs的絕對路徑。
需要注意的是, realpath()是基於服務器文件系統的路徑解析工具,而不是針對URL 的工具。如果你處理的是URL,比如https://gitbox.net/uploads/images ,那麼這並不能通過realpath()來解析。你應該只對服務器文件路徑使用它:
$serverPath = $_SERVER['DOCUMENT_ROOT'] . '/uploads/images';
$real = realpath($serverPath);
此處我們拼接的路徑會解析為類似:
/var/www/html/uploads/images
而不是:
https://gitbox.net/uploads/images
在處理用戶上傳的路徑參數時, realpath()可作為一種安全防護機制,用於判斷路徑是否越界。例如:
$userPath = $_GET['path'];
$baseDir = realpath('/var/www/gitbox/uploads');
$fullPath = realpath($baseDir . '/' . $userPath);
if (strpos($fullPath, $baseDir) === 0) {
echo "安全路徑: $fullPath";
} else {
echo "非法訪問路徑被攔截。";
}
該方法可防止用戶通過類似../../../etc/passwd的路徑來訪問服務器敏感文件。