萬盛學電腦網

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

PHP 檔案操作類封裝與檔案下載功能完整實作

檔案操作類:CFile 完整實作

封裝常用檔案操作(讀/寫/附加/路徑設定),統一錯誤處理、權限檢查、資源管理。

<?php
class CFile {
    protected string $path;
    
    // 錯誤訊息常數
    const ERR_NOT_FOUND = '檔案不存在';
    const ERR_PERMISSION = '權限不足';
    const ERR_OPEN = '無法開啟檔案';
    const ERR_CLOSE = '無法關閉檔案';

    public function __construct(string $path = '') {
        if ($path !== '') $this->setPath($path);
    }

    public function setPath(string $path): void {
        $this->path = $path;
    }

    public function getPath(): string {
        return $this->path;
    }

    /**
     * 內部開啟檔案,統一權限檢查與錯誤處理
     */
    private function openFile(string $mode): ?resource {
        if (!file_exists($this->path)) {
            throw new RuntimeException(self::ERR_NOT_FOUND);
        }
        
        $readable = in_array($mode[0], ['r', 'a', 'x', 'c']) || str_contains($mode, '+');
        $writable = in_array($mode[0], ['w', 'a', 'x', 'c']) || str_contains($mode, '+');
        
        if ($readable && !is_readable($this->path)) {
            throw new RuntimeException(self::ERR_PERMISSION);
        }
        if ($writable && !is_writable($this->path)) {
            throw new RuntimeException(self::ERR_PERMISSION);
        }
        
        $fp = @fopen($this->path, $mode);
        if ($fp === false) {
            throw new RuntimeException(self::ERR_OPEN);
        }
        return $fp;
    }

    /**
     * 讀取整個檔案內容
     */
    public function readAll(): string {
        $fp = $this->openFile('r');
        $content = stream_get_contents($fp);
        fclose($fp);
        return $content;
    }

    /**
     * 逐行讀取(Generator,記憶體友善)
     */
    public function readLines(): Generator {
        $fp = $this->openFile('r');
        while (($line = fgets($fp)) !== false) {
            yield rtrim($line, "\r\n");
        }
        fclose($fp);
    }

    /**
     * 寫入(覆蓋)
     */
    public function write(string $data): int {
        $fp = $this->openFile('w');
        $bytes = fwrite($fp, $data);
        fclose($fp);
        return $bytes;
    }

    /**
     * 附加寫入
     */
    public function append(string $data): int {
        $fp = $this->openFile('a');
        $bytes = fwrite($fp, $data);
        fclose($fp);
        return $bytes;
    }

    /**
     * 安全寫入:寫入暫存檔 → 原子性重命名
     */
    public function writeAtomic(string $data): bool {
        $tmpPath = $this->path . '.tmp.' . bin2hex(random_bytes(8));
        $fp = @fopen($tmpPath, 'w');
        if (!$fp) return false;
        
        $bytes = fwrite($fp, $data);
        fclose($fp);
        
        if ($bytes === false) {
            @unlink($tmpPath);
            return false;
        }
        
        return @rename($tmpPath, $this->path);
    }

    /**
     * 檔案資訊
     */
    public function getInfo(): array {
        if (!file_exists($this->path)) return [];
        return [
            'path'      => $this->path,
            'size'      => filesize($this->path),
            'mtime'     => filemtime($this->path),
            'mime'      => mime_content_type($this->path),
            'extension' => pathinfo($this->path, PATHINFO_EXTENSION),
            'readable'  => is_readable($this->path),
            'writable'  => is_writable($this->path),
        ];
    }
}

// ===== 使用範例 =====
$file = new CFile(__DIR__ . '/data/test.txt');

// 寫入
$file->write("Hello World!\n");

// 附加
$file->append("Appended line.\n");

// 讀取全部
echo $file->readAll();

// 逐行處理大檔案
foreach ($file->readLines() as $lineNum => $line) {
    echo "Line $lineNum: $line\n";
}

// 原子性寫入(避免部分寫入被讀取)
$file->writeAtomic(json_encode(['status' => 'ok', 'time' => time()]));

// 檔案資訊
print_r($file->getInfo());
?>

檔案下載功能實作

基礎下載(適用小檔案)

<?php
function downloadFile(string $filePath, string $downloadName = ''): void {
    if (!is_file($filePath) || !is_readable($filePath)) {
        http_response_code(404);
        exit('File not found');
    }
    
    $downloadName = $downloadName ?: basename($filePath);
    $size = filesize($filePath);
    $mime = mime_content_type($filePath) ?: 'application/octet-stream';
    
    // 快取控制
    header('Expires: 0');
    header('Pragma: public');
    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
    header('Cache-Control: public');
    
    // 內容資訊
    header("Content-Length: $size");
    header("Content-Type: $mime");
    header('Content-Disposition: attachment; filename="' . rawurlencode($downloadName) . '"');
    header('Content-Transfer-Encoding: binary');
    
    // 輸出
    readfile($filePath);
    exit;
}

// 使用
downloadFile('/var/www/files/report.pdf', '月報表_2024.pdf');

大檔案分塊下載(支援斷點續傳 Range Request)

<?php
function downloadLargeFile(string $filePath, string $downloadName = ''): void {
    if (!is_file($filePath) || !is_readable($filePath)) {
        http_response_code(404);
        exit('File not found');
    }
    
    $downloadName = $downloadName ?: basename($filePath);
    $size = filesize($filePath);
    $mime = mime_content_type($filePath) ?: 'application/octet-stream';
    
    // 處理 Range 請求
    $rangeStart = 0;
    $rangeEnd = $size - 1;
    $partial = false;
    
    if (isset($_SERVER['HTTP_RANGE'])) {
        $range = $_SERVER['HTTP_RANGE'];
        if (preg_match('/bytes=(\d+)-(\d*)/', $range, $matches)) {
            $rangeStart = (int)$matches[1];
            $rangeEnd = $matches[2] !== '' ? (int)$matches[2] : $size - 1;
            $partial = true;
        }
    }
    
    // 邊界檢查
    $rangeStart = max(0, min($rangeStart, $size - 1));
    $rangeEnd = max($rangeStart, min($rangeEnd, $size - 1));
    $contentLength = $rangeEnd - $rangeStart + 1;
    
    // Header
    header('Accept-Ranges: bytes');
    header("Content-Length: $contentLength");
    header("Content-Type: $mime");
    header('Content-Disposition: attachment; filename="' . rawurlencode($downloadName) . '"');
    header('Content-Transfer-Encoding: binary');
    
    if ($partial) {
        http_response_code(206); // Partial Content
        header("Content-Range: bytes $rangeStart-$rangeEnd/$size");
    } else {
        http_response_code(200);
    }
    
    // 分塊輸出
    $fp = fopen($filePath, 'rb');
    fseek($fp, $rangeStart);
    
    $bufferSize = 8192;
    while (!feof($fp) && $contentLength > 0) {
        $readSize = min($bufferSize, $contentLength);
        echo fread($fp, $readSize);
        $contentLength -= $readSize;
        
        // 釋放輸出緩衝,避免記憶體累積
        if (ob_get_level()) ob_flush();
        flush();
    }
    fclose($fp);
    exit;
}

安全性檢查清單

  • 路徑遍歷防護:realpath($userInput) 並在允許根目錄下
  • MIME 類型驗證:mime_content_type() + 白名單,不信任副檔名
  • 檔案大小限制:下載前檢查 filesize() 不超限制
  • 權限控制:結合使用者認證/授權檢查
  • 速率限制:Token Bucket 或漏桶演算法限制下載頻寬
  • 記錄審計日誌:誰、何時、下載什麼、IP、User-Agent

Nginx X-Accel-Redirect / Apache X-Sendfile(高效能下載)

將檔案傳輸交給 Web 伺服器,PHP 僅驗證權限並發送特殊 Header:

<?php
// Nginx 設定需包含:location /protected/ { internal; alias /var/www/files/; }
function downloadXAccel(string $internalPath, string $downloadName): void {
    // $internalPath 為 Nginx internal location 對應的內部路徑
    header('X-Accel-Redirect: ' . $internalPath);
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename="' . rawurlencode($downloadName) . '"');
    header('Content-Length: ' . filesize($downloadName)); // 可選
    exit;
}

總結

  • 封裝 CFile 類別統一管理檔案操作、錯誤處理、原子性寫入
  • 小檔案用 readfile(),大檔案用分塊輸出支援 Range 斷點續傳
  • 高流量下載交給 Nginx/Apache X-Accel-Redirect/X-Sendfile 卸載 PHP
  • 務必實作路徑遍歷防護、MIME 驗證、權限控制、審計日誌
  • 現代專案建議使用 Flysystem 抽象層支援本地/S3/FTP/SFTP 統一介面
copyright © 萬盛學電腦網 all rights reserved