PHP 提供超過 60 個檔案系統函數,涵蓋路徑解析、讀寫、權限、時間、鎖定、串流、目錄掃描等。本文分類整理高頻函數,附最小可執行範例,供開發速查。
$path = '/home/user/project/index.php';
echo basename($path); // index.php
echo basename($path, '.php'); // index
echo dirname($path); // /home/user/project
print_r(pathinfo($path));
/*
Array
(
[dirname] => /home/user/project
[basename] => index.php
[extension] => php
[filename] => index
)
*/
$file = 'data.log';
echo "存在:", file_exists($file) ? '是' : '否', PHP_EOL;
echo "是檔案:", is_file($file) ? '是' : '否', PHP_EOL;
echo "是目錄:", is_dir($file) ? '是' : '否', PHP_EOL;
echo "可讀:", is_readable($file) ? '是' : '否', PHP_EOL;
echo "可寫:", is_writable($file) ? '是' : '否', PHP_EOL;
echo "大小:", filesize($file), " bytes", PHP_EOL;
echo "類型:", filetype($file), PHP_EOL; // file/dir/link
echo "修改時間:", date('Y-m-d H:i:s', filemtime($file)), PHP_EOL;
echo "存取時間:", date('Y-m-d H:i:s', fileatime($file)), PHP_EOL;
echo "權限:", substr(sprintf('%o', fileperms($file)), -4), PHP_EOL; // 0644
echo "擁有者 UID:", fileowner($file), PHP_EOL;
echo "群組 GID:", filegroup($file), PHP_EOL;
// 讀整個檔案到字串
$content = file_get_contents('config.json');
$data = json_decode($content, true);
// 寫入字串到檔案(原子性:臨時檔 + rename)
file_put_contents('config.json', json_encode($data, JSON_PRETTY_PRINT), LOCK_EX);
// 讀整個檔案到陣列(每行一元素)
$lines = file('access.log', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
// 逐行處理大檔案(低記憶體)
$fp = fopen('huge.log', 'r');
while (($line = fgets($fp)) !== false) {
// 處理 $line
}
fclose($fp);
// 二進制安全讀寫
$bin = fread($fp, 8192);
fwrite($fp, $bin);
// 寫入 CSV
$fp = fopen('users.csv', 'w');
fputcsv($fp, ['id', 'name', 'email']);
fputcsv($fp, [1, 'Alice', 'alice@example.com']);
fclose($fp);
// 讀取 CSV
$fp = fopen('users.csv', 'r');
while (($row = fgetcsv($fp)) !== false) {
print_r($row);
}
fclose($fp);
// 掃描目錄(含 . 與 ..)
$entries = scandir('/var/www');
print_r($entries);
// 遞迴掃描(SPL)
$iter = new RecursiveIteratorIterator(new RecursiveDirectoryIterator('/var/www', FilesystemIterator::SKIP_DOTS));
foreach ($iter as $file) {
echo $file->getPathname(), PHP_EOL;
}
// 建立目錄(遞迴、權限)
mkdir('/tmp/a/b/c', 0755, true);
// 刪除目錄(必須為空)
rmdir('/tmp/a/b/c');
// 刪除檔案
unlink('temp.txt');
// 重命名/移動
rename('old.txt', 'new.txt');
// 符號連結
symlink('/target/path', '/link/path');
echo readlink('/link/path'); // /target/path
$fp = fopen('counter.txt', 'c+'); // 開啟/建立,指標在開頭
if (flock($fp, LOCK_EX)) { // 獨佔鎖
$count = (int)fread($fp, 1024);
ftruncate($fp, 0);
rewind($fp);
fwrite($fp, ++$count);
flock($fp, LOCK_UN); // 釋放鎖
} else {
echo "無法取得鎖";
}
fclose($fp);
echo "可用:", disk_free_space('/'), " bytes", PHP_EOL;
echo "總計:", disk_total_space('/'), " bytes", PHP_EOL;
$tmp = tmpfile(); // 建立臨時檔,關閉自動刪除
fwrite($tmp, "temporary data");
fseek($tmp, 0);
echo fread($tmp, 1024);
fclose($tmp);
$name = tempnam(sys_get_temp_dir(), 'myapp_'); // 取得唯一檔名
file_put_contents($name, "data");
// 使用完畢需自行 unlink($name)
$proc = popen('ls -la', 'r');
while (!feof($proc)) {
echo fgets($proc);
}
pclose($proc);
// 記憶體串流(無實體檔)
$mem = fopen('php://memory', 'r+');
fwrite($mem, "in memory");
rewind($mem);
echo stream_get_contents($mem);
fclose($mem);
clearstatcache(); // 清除 filemtime、filesize、is_file 等快取
// 針對特定檔案
clearstatcache(true, '/path/to/file');
檔案系統操作是後端開發基石。建議:
file_get_contents/file_put_contents/file 簡化邏輯。fopen 族函數。pathinfo、realpath、DIRECTORY_SEPARATOR。stat/lstat 取得完整資訊。allow_url_fopen,遠端資源改用 cURL/Guzzle。