萬盛學電腦網

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

PHP 文件遍歷與處理類庫:FindFile 基類與 UnsetBOM 實戰應用

一、架構設計:模板方法模式

採用 模板方法模式 分離「遍歷邏輯」與「具體處理」:

  • FindFile:基類,負責遞歸遍歷目錄、深度控制、文件收集
  • 子類重寫 handle($file) 實現具體業務(如去 BOM、掃描病毒、統計代碼行)

二、核心基類:FindFile

<?php
/**
 * 文件遍歷基類
 * 支持最大深度控制,收集所有文件路徑
 */
class FindFile {
    public $files = [];      // 收集的文件路徑
    protected $maxdepth = 0; // 0 = 無限制

    /** 入口方法
     * @param string $spath 起始目錄
     * @param int $maxdepth 最大深度
     */
    public function process($spath, $maxdepth = 0) {
        $this->maxdepth = (is_numeric($maxdepth) && $maxdepth > 0) ? $maxdepth : 0;
        $this->files = [];
        $this->traversing($spath);
    }

    /** 遞歸遍歷(模板方法核心) */
    private function traversing($spath, $depth = 1) {
        if (!is_dir($spath) || !$handle = opendir($spath)) return;

        while (($file = readdir($handle)) !== false) {
            if ($file === '.' || $file === '..') continue;
            $curfile = $spath . '/' . $file;

            if (is_dir($curfile)) {
                // 目錄:判斷深度後遞歸
                if ($this->maxdepth === 0 || $depth < $this->maxdepth) {
                    $this->traversing($curfile, $depth + 1);
                }
            } else {
                // 文件:交給 handle 處理
                $this->handle($curfile);
            }
        }
        closedir($handle);
    }

    /** 鉤子方法:子類重寫實現具體處理
     * @param string $file 文件絕對路徑
     */
    protected function handle($file) {
        $this->files[] = $file; // 默認僅收集路徑
    }
}
?>

三、實戰子類:UnsetBOM - 批量清除 UTF-8 BOM

UTF-8 BOM (EF BB BF) 會導致 PHP 輸出異常、JSON 解析失敗、HTTP Header 提前發送等問題。

<?php
/**
 * 清除 UTF-8 BOM 處理器
 * 繼承 FindFile,指定處理文件類型
 */
class UnsetBom extends FindFile {
    private $filetype = []; // 允許處理的副檔名

    public function __construct(array $filetype = []) {
        $this->filetype = $filetype;
    }

    protected function handle($file) {
        // 雙重過濾:副檔名 + 實際 BOM 檢測
        if ($this->check_ext($file) && $this->check_utf8bom($file)) {
            $this->clear_utf8bom($file);
            $this->files[] = $file; // 記錄已處理文件
        }
    }

    /** 檢測 BOM:讀取前 3 字節 */
    private function check_utf8bom($file) {
        $content = file_get_contents($file, false, null, 0, 3);
        return strlen($content) === 3 &&
               ord($content[0]) === 0xEF &&
               ord($content[1]) === 0xBB &&
               ord($content[2]) === 0xBF;
    }

    /** 清除 BOM:去掉前 3 字節重寫 */
    private function clear_utf8bom($file) {
        $content = file_get_contents($file);
        file_put_contents($file, substr($content, 3), LOCK_EX);
    }

    /** 副檔名過濾(不區分大小寫) */
    private function check_ext($file) {
        if (empty($this->filetype)) return true; // 無限制則全處理
        $ext = strtolower(pathinfo($file, PATHINFO_EXTENSION));
        return in_array($ext, $this->filetype);
    }
}
?>

四、使用示例

<?php
require 'FindFile.class.php';
require 'UnsetBom.class.php';

$project_root = dirname(__FILE__);
// 處理 php、css、js 文件
$cleaner = new UnsetBom(['php', 'css', 'js', 'html', 'xml', 'json']);
$cleaner->process($project_root);

echo "已清除 BOM 的文件 (" . count($cleaner->files) . "):\n";
print_r($cleaner->files);
?>

五、擴展應用:更多實用處理器

1. 代碼行數統計器

class CodeCounter extends FindFile {
    private $total_lines = 0;
    private $code_lines = 0;
    private $comment_lines = 0;
    private $blank_lines = 0;

    protected function handle($file) {
        if (!$this->check_ext($file)) return;
        $content = file_get_contents($file);
        $lines = explode("\n", $content);
        $this->total_lines += count($lines);
        foreach ($lines as $line) {
            $trimmed = trim($line);
            if ($trimmed === '') $this->blank_lines++;
            elseif (strpos($trimmed, '//') === 0 || strpos($trimmed, '#') === 0) $this->comment_lines++;
            else $this->code_lines++;
        }
    }
    // ... getter 方法
}

2. 惡意代碼掃描器

class MalwareScanner extends FindFile {
    private $patterns = [
        '/eval\s*\(/i', '/base64_decode\s*\(/i', '/gzinflate\s*\(/i',
        '/shell_exec\s*\(/i', '/system\s*\(/i', '/passthru\s*\(/i'
    ];
    public $suspects = [];

    protected function handle($file) {
        if (!$this->check_ext($file)) return;
        $content = file_get_contents($file);
        foreach ($this->patterns as $pattern) {
            if (preg_match($pattern, $content)) {
                $this->suspects[$file][] = $pattern;
                break;
            }
        }
    }
}

六、效能優化建議

  • 大目錄遍歷:使用 RecursiveDirectoryIterator + RecursiveIteratorIterator 替代 opendir/readdir,C 層實現更快
  • 內存控制:$files 收集大量路徑會佔用內存,改用 Generator (yield) 流式處理
  • 並行處理:配合 pcntl_fork 或進程池並行處理多個子目錄
  • 緩存結果:基於文件 mtime 緩存掃描結果,避免重複掃描未變更目錄

這套類庫結構清晰、擴展性強,是構建各類文件系統維護工具的理想基礎。

copyright © 萬盛學電腦網 all rights reserved