萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 檔案與目錄操作完全指南:8 大核心場景實戰

概覽

PHP 提供豐富的檔案系統函數,涵蓋開啟、讀寫、權限、刪除、目錄遍歷等。本文整理 8 大常見場景,附上最佳實踐與錯誤處理模式。

1. 開啟檔案:fopen()

$fp = fopen('data.txt', 'rb'); // 二進位讀取,跨平台安全
$fp = fopen('../data.txt', 'rb'); // 相對路徑
$fp = fopen('https://example.com/file.csv', 'rb'); // 遠程 (需 allow_url_fopen=On)

// 模式速查
// r  讀取,指標在開頭
// r+ 讀寫,指標在開頭
// w  寫入,截斷為零長度,不存在則建立
// w+ 讀寫,截斷
// a  追加,指標在結尾
// a+ 讀寫追加
// b  二進位模式 (Windows 必加)
// x  獨佔建立,存在則失敗 (PHP 4.3.2+)

2. 關閉檔案:fclose()

if ($fp) {
    fclose($fp); // 釋放資源、刷新緩衝區
}

腳本結束會自動關閉,但長腳本/大量檔案操作請顯式關閉,避免檔案描述符耗盡。

3. 讀取檔案

函數用途範例
fgets($fp, 1024)逐行讀取 (文字檔)while (($line = fgets($fp)) !== false) { ... }
fgetcsv($fp)解析 CSV 行while (($row = fgetcsv($fp)) !== false) { ... }
fread($fp, 8192)二進位塊讀取大檔案分塊處理
file_get_contents()一次讀全檔小檔案、簡單場景
file()整檔讀入陣列 (每行一元素)$lines = file('log.txt', FILE_IGNORE_NEW_LINES);

4. 寫入檔案

$fp = fopen('log.txt', 'ab'); // 追加二進位
if ($fp) {
    fwrite($fp, "新行內容\n");
    fclose($fp);
}

// 簡易寫入 (原子性較差)
file_put_contents('config.json', json_encode($config, JSON_PRETTY_PRINT));
// 原子寫入 (避免部分寫入被讀取)
$tmp = tempnam(sys_get_temp_dir(), 'cfg');
file_put_contents($tmp, $content);
rename($tmp, 'config.json'); // rename 在同檔案系統是原子的

5. 檔案狀態與資訊

$file = 'data.txt';
var_dump([
    'exists' => file_exists($file),
    'is_file' => is_file($file),
    'is_dir' => is_dir($file),
    'is_readable' => is_readable($file),
    'is_writable' => is_writable($file),
    'size' => filesize($file),
    'perms' => substr(sprintf('%o', fileperms($file)), -4), // 八進位權限
    'owner' => fileowner($file), // UID
    'group' => filegroup($file), // GID
    'mtime' => date('Y-m-d H:i:s', filemtime($file)),
    'atime' => date('Y-m-d H:i:s', fileatime($file)),
    'ctime' => date('Y-m-d H:i:s', filectime($file)),
]);

6. 刪除與重命名

unlink('old.txt'); // 刪除檔案
rename('old.txt', 'new.txt'); // 重命名/移動 (跨目錄需同檔案系統)
rename('dir/old', 'dir/new'); // 目錄亦適用

7. 目錄操作

// 建立目錄 (遞迴、權限)
mkdir('storage/logs/2024', 0755, true);

// 掃描目錄
$files = scandir('storage/logs'); // 含 . 和 ..
$files = array_diff(scandir('storage/logs'), ['.', '..']);

// 遞迴遍歷 (SPL)
$iterator = new RecursiveIteratorIterator(
    new RecursiveDirectoryIterator('storage', FilesystemIterator::SKIP_DOTS)
);
foreach ($iterator as $file) {
    if ($file->isFile()) {
        echo $file->getPathname() . "\n";
    }
}

// 刪除目錄 (需先清空)
function rmdir_recursive(string $dir): bool {
    $it = new RecursiveDirectoryIterator($dir, FilesystemIterator::SKIP_DOTS);
    foreach (new RecursiveIteratorIterator($it, RecursiveIteratorIterator::CHILD_FIRST) as $file) {
        $file->isDir() ? rmdir($file->getPathname()) : unlink($file->getPathname());
    }
    return rmdir($dir);
}

8. 路徑處理與最佳實踐

// 路徑分隔符統一用 DIRECTORY_SEPARATOR 或 '/'
$path = 'storage' . DIRECTORY_SEPARATOR . 'logs';

// 取得檔名、副檔名、目錄
$filename = basename($path); // 檔名
$dirname = dirname($path);   // 目錄
$ext = pathinfo($path, PATHINFO_EXTENSION); // 副檔名

// 實際路徑解析 (解析符號連結、相對路徑)
$real = realpath($path); // 失敗回傳 false

// 臨時檔案/目錄
$tmpFile = tmpfile(); // 資源,關閉自動刪除
$tmpName = tempnam(sys_get_temp_dir(), 'prefix_'); // 需手動 unlink

錯誤處理模式

function safe_read(string $path): ?string {
    $fp = @fopen($path, 'rb');
    if (!$fp) {
        error_log("無法開啟檔案: $path");
        return null;
    }
    try {
        $content = stream_get_contents($fp);
    } finally {
        fclose($fp);
    }
    return $content;
}
copyright © 萬盛學電腦網 all rights reserved