基礎函數速查表
| 函數 | 用途 | 回傳值 |
basename(path, suffix) | 取得檔名(可選移除副檔名) | 字串 |
dirname(path) | 取得目錄路徑(去除檔名) | 字串 |
pathinfo(path, options) | 解析路徑為關聯陣列 | 陣列/字串 |
basename() - 取得檔名
<?php
$path = "/home/httpd/html/index.php";
$file = basename($path); // "index.php"
$file = basename($path, ".php"); // "index"
// Windows 同時支援 / 和 \ 作為分隔符
?>
dirname() - 取得目錄路徑
<?php
echo dirname("c:/testweb/home.php"); // c:/testweb
echo dirname("/testweb/home.php"); // /testweb
// 實用技巧:取得上層目錄
$current_dir = dirname(__FILE__); // 當前檔案所在目錄
$parent_dir = dirname(dirname(__FILE__)); // 上一層目錄
?>
pathinfo() - 完整路徑解析
<?php
// 完整解析
print_r(pathinfo("/testweb/test.txt"));
/* 輸出:
Array (
[dirname] => /testweb
[basename] => test.txt
[extension] => txt
[filename] => test // PHP 5.2.0+ 可用
)
*/
// 只取特定部分(常數:PATHINFO_DIRNAME, PATHINFO_BASENAME, PATHINFO_EXTENSION, PATHINFO_FILENAME)
echo pathinfo("/testweb/test.txt", PATHINFO_BASENAME); // test.txt
echo pathinfo("/testweb/test.txt", PATHINFO_EXTENSION); // txt
?>
跨平台路徑處理最佳實踐
- 使用
DIRECTORY_SEPARATOR 常數而非硬編碼分隔符
- 路徑拼接推薦
join(DIRECTORY_SEPARATOR, [$dir, $file])
- 處理 URL 路徑時使用
parse_url() 而非檔案系統函數
常見應用場景
<?php
// 自動載入器中解析類別檔案路徑
$class_file = __DIR__ . '/src/' . str_replace('\\', '/', $class) . '.php';
$dir = dirname($class_file);
if (!is_dir($dir)) {
mkdir($dir, 0755, true); // 遞歸建立目錄
}
// 上傳檔案重新命名(保留副檔名)
$ext = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);
$new_name = uniqid('upload_') . '.' . $ext;
?>