萬盛學電腦網

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

PHP 檔案讀寫刪除複製核心操作完整指南

PHP 檔案系統操作基礎

PHP 提供豐富的檔案系統函數,掌握核心操作是後端開發基本功。本文系統整理「寫入、讀取、刪除、複製」四大核心操作,搭配錯誤處理、鎖定機制、資源管理最佳實踐。

一、檔案寫入

基本寫入模式對照

模式說明指標位置截斷檔案建立新檔
w唯寫開頭是是
a唯寫 (附加)結尾否是
w+讀寫開頭是是
a+讀寫 (附加)結尾否是
x唯寫 (獨佔建立)開頭否僅不存在時
c唯寫 (不截斷)開頭否是

安全寫入最佳實踐

<?php
function safeWrite(string $filepath, string $data, bool $append = false): bool
{
    $dir = dirname($filepath);
    if (!is_dir($dir)) {
        if (!mkdir($dir, 0755, true)) {
            error_log("建立目錄失敗: $dir");
            return false;
        }
    }

    $flags = $append ? (LOCK_EX | FILE_APPEND) : LOCK_EX;
    $bytes = file_put_contents($filepath, $data, $flags);
    
    if ($bytes === false) {
        error_log("寫入失敗: $filepath");
        return false;
    }
    
    return true;
}

// 使用範例
safeWrite('logs/app.log', date('Y-m-d H:i:s') . " 用戶登入\n", true); // 附加模式
safeWrite('config/settings.json', json_encode($config, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE)); // 覆寫模式
?>

大檔案分塊寫入 (避免記憶體溢出)

<?php
function writeLargeFile(string $source, string $dest, int $chunkSize = 8192): bool
{
    $src = fopen($source, 'rb');
    $dst = fopen($dest, 'wb');
    
    if (!$src || !$dst) return false;
    
    while (!feof($src)) {
        $chunk = fread($src, $chunkSize);
        if (fwrite($dst, $chunk) === false) {
            fclose($src);
            fclose($dst);
            return false;
        }
    }
    
    fclose($src);
    fclose($dst);
    return true;
}
?>

二、檔案讀取

多種讀取方式適用場景

函數/方法適用場景記憶體效能
file_get_contents()小檔案、API 回應、配置檔全載入最快 (內部優化)
file()逐行處理、日誌分析全載入陣列中等
fopen() + fgets()大檔案逐行、CSV 解析單行好
fopen() + fread()二進位檔案、分塊處理分塊大小好
SplFileObject物件導向、CSV 迭代單行好
readfile()直接輸出下載、圖片代理不佔用 PHP 記憶體最佳

大檔案逐行處理範例 (CSV 匯入)

<?php
function importCsv(string $filepath, callable $rowHandler): int
{
    $handle = fopen($filepath, 'rb');
    if (!$handle) throw new Exception("無法開啟檔案: $filepath");
    
    $count = 0;
    // 設定 CSV 控制字元
    while (($row = fgetcsv($handle, 0, ',', '"', '\\')) !== false) {
        // 跳過空行
        if (array_filter($row) === []) continue;
        
        try {
            $rowHandler($row, $count);
            $count++;
        } catch (Throwable $e) {
            error_log("第 $count 行處理失敗: " . $e->getMessage());
            // 可決定是否繼續或中止
        }
    }
    
    fclose($handle);
    return $count;
}

// 使用
$imported = importCsv('data/users.csv', function(array $row, int $index) {
    // $row = ['姓名', 'Email', '電話', ...]
    User::create([
        'name' => $row[0],
        'email' => $row[1],
        'phone' => $row[2],
    ]);
});
echo "匯入 $imported 筆資料";
?>

三、檔案刪除

安全刪除與目錄清理

<?php
function safeDelete(string $path): bool
{
    // 正規化路徑,防止目錄遍歷
    $realPath = realpath($path);
    if (!$realPath || !file_exists($realPath)) {
        return true; // 不存在視為成功
    }
    
    // 安全檢查:確保在允許目錄內
    $allowedRoot = realpath(__DIR__ . '/storage');
    if (strpos($realPath, $allowedRoot) !== 0) {
        error_log("嘗試刪除受保護路徑: $realPath");
        return false;
    }
    
    if (is_dir($realPath)) {
        // 遞歸刪除目錄
        $files = new RecursiveIteratorIterator(
            new RecursiveDirectoryIterator($realPath, RecursiveDirectoryIterator::SKIP_DOTS),
            RecursiveIteratorIterator::CHILD_FIRST
        );
        foreach ($files as $file) {
            $file->isDir() ? rmdir($file->getPathname()) : unlink($file->getPathname());
        }
        return rmdir($realPath);
    }
    
    return unlink($realPath);
}

// 清理超過 30 天的暫存檔
function cleanupTemp(string $dir, int $maxAge = 2592000): int
{
    $deleted = 0;
    $now = time();
    
    $iterator = new RecursiveIteratorIterator(
        new RecursiveDirectoryIterator($dir, RecursiveDirectoryIterator::SKIP_DOTS)
    );
    
    foreach ($iterator as $file) {
        if ($file->isFile() && ($now - $file->getMTime()) > $maxAge) {
            if (unlink($file->getPathname())) $deleted++;
        }
    }
    
    return $deleted;
}
?>

四、檔案複製與移動

複製進階技巧

<?php
function smartCopy(string $source, string $dest, bool $overwrite = false): bool
{
    if (!file_exists($source)) {
        throw new Exception("來源檔案不存在: $source");
    }
    
    if (file_exists($dest)) {
        if (!$overwrite) {
            throw new Exception("目標檔案已存在: $dest");
        }
        if (!unlink($dest)) {
            throw new Exception("無法覆寫目標檔案: $dest");
        }
    }
    
    $destDir = dirname($dest);
    if (!is_dir($destDir)) {
        mkdir($destDir, 0755, true);
    }
    
    // copy() 會自動處理大檔案串流,不佔用記憶體
    if (!copy($source, $dest)) {
        throw new Exception("複製失敗: $source -> $dest");
    }
    
    // 保留原檔權限與時間
    $stat = stat($source);
    chmod($dest, $stat['mode'] & 0777);
    touch($dest, $stat['mtime']);
    
    return true;
}

// 移動 (跨裝置自動 fallback 為複製+刪除)
function smartMove(string $source, string $dest, bool $overwrite = false): bool
{
    if (!file_exists($source)) return false;
    
    if (file_exists($dest)) {
        if (!$overwrite) return false;
        unlink($dest);
    }
    
    $destDir = dirname($dest);
    if (!is_dir($destDir)) mkdir($destDir, 0755, true);
    
    // 同檔案系統用 rename (原子操作、極快)
    if (@rename($source, $dest)) return true;
    
    // 跨檔案系統 fallback
    return smartCopy($source, $dest, true) && unlink($source);
}
?>

五、實用工具函數庫

<?php
class FileUtil
{
    /** 取得人類可讀檔案大小 */
    public static function humanSize(int $bytes): string
    {
        $units = ['B', 'KB', 'MB', 'GB', 'TB'];
        $i = 0;
        while ($bytes >= 1024 && $i < count($units) - 1) {
            $bytes /= 1024;
            $i++;
        }
        return round($bytes, 2) . ' ' . $units[$i];
    }

    /** 取得副檔名 (小寫) */
    public static function extension(string $path): string
    {
        return strtolower(pathinfo($path, PATHINFO_EXTENSION));
    }

    /** 安全檔名 (移除特殊字元) */
    public static function sanitizeFilename(string $filename): string
    {
        $filename = basename($filename);
        $filename = preg_replace('/[^a-zA-Z0-9._-]/', '_', $filename);
        return substr($filename, 0, 255);
    }

    /** 計算檔案雜湊 (支援大檔) */
    public static function hashFile(string $path, string $algo = 'sha256'): string
    {
        $hash = hash_init($algo);
        $handle = fopen($path, 'rb');
        while (!feof($handle)) {
            hash_update($hash, fread($handle, 8192));
        }
        fclose($handle);
        return hash_final($hash);
    }

    /** 取得 MIME 類型 */
    public static function mimeType(string $path): string
    {
        $finfo = finfo_open(FILEINFO_MIME_TYPE);
        $mime = finfo_file($finfo, $path);
        finfo_close($finfo);
        return $mime ?: 'application/octet-stream';
    }
}
?>

錯誤處理與除錯技巧

  1. 永遠檢查回傳值:fopen、fwrite、copy、unlink 皆可能回傳 false
  2. 使用 error_get_last():函數失敗時獲取詳細錯誤
  3. 啟用嚴格模式:declare(strict_types=1) 避免隱性轉型
  4. 記錄操作日誌:關鍵寫入/刪除操作記錄審計追蹤

總結

PHP 檔案操作看似簡單,但生產環境需考慮:併發安全 (flock)、大檔記憶體管理 (串流)、路徑安全 (realpath)、錯誤處理、權限保留、跨平台相容。善用 file_put_contents() (簡單)、SplFileObject (OOP)、readfile() (輸出) 等現代 API,配合自訂工具類,能構建健壯的檔案處理層。

copyright © 萬盛學電腦網 all rights reserved