處理檔案路徑時,常需取得目錄名、檔名、副檔名。PHP 提供三個核心函數,各有專長。
string basename ( string $path [, string $suffix = "" ] )
$suffix:若檔名以此結尾,則移除 (常用於去除副檔名)。/ 和 \ 皆視為分隔符;其他系統僅 /。<?php $path = '/home/httpd/html/index.php'; echo basename($path); // index.php echo basename($path, '.php'); // index ?>
string dirname ( string $path )
require dirname(__FILE__) . '/config.php'; (PHP 5.3+ 建議用 __DIR__)。dirname(dirname(__FILE__)) 取得上兩層目錄。<?php
echo dirname('c:/testweb/home.php'); // c:/testweb
echo dirname('/testweb/home.php'); // /testweb
echo dirname(__DIR__); // 專案根目錄 (若檔案在 src/ 下)
?>
array|string pathinfo ( string $path [, int $options = PATHINFO_DIRNAME | PATHINFO_BASENAME | PATHINFO_EXTENSION | PATHINFO_FILENAME ] )
$options 回傳關聯陣列:dirname, basename, extension (副檔名), filename (不含副檔名的檔名, PHP 5.2+)。$options 旗標 (可用 | 組合) 時回傳對應字串。<?php
$path = '/testweb/test.txt';
print_r(pathinfo($path));
/*
Array
(
[dirname] => /testweb
[basename] => test.txt
[extension] => txt
[filename] => test
)
*/
// 只取副檔名
echo pathinfo($path, PATHINFO_EXTENSION); // txt
// 只取檔名 (不含副檔名)
echo pathinfo($path, PATHINFO_FILENAME); // test
// 組合旗標
print_r(pathinfo($path, PATHINFO_DIRNAME | PATHINFO_BASENAME));
/*
Array
(
[dirname] => /testweb
[basename] => test.txt
)
*/
?>
| 需求 | 推薦函數/寫法 |
|---|---|
| 取得目前腳本目錄 | __DIR__ (魔術常數, PHP 5.3+) |
| 取得專案根目錄 | dirname(__DIR__, 2) (PHP 7.0+ 支援層級參數) 或 realpath(__DIR__ . '/../') |
| 安全包含檔案 | require __DIR__ . '/../config.php'; |
| 上傳檔案重命名保留副檔名 | $ext = pathinfo($filename, PATHINFO_EXTENSION); $new = uniqid() . '.' . $ext; |
| 判斷副檔名是否允許 | in_array(pathinfo($name, PATHINFO_EXTENSION), $allowed, true) |
| 取得不含副檔名的檔名 | pathinfo($name, PATHINFO_FILENAME) |
pathinfo() **不感知實際檔案系統**,純字串操作。mb_pathinfo() 自行實作。parse_url(),而非此三函數。