萬盛學電腦網

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

PHP 文件系統操作實戰:目錄遍歷、文件拷貝與權限管理

核心函數速查

  • opendir() / readdir() / closedir():目錄句柄操作三部曲。
  • scandir():一次性返回目錄下所有文件名數組(含 . ..)。
  • glob():模式匹配獲取文件列表,如 glob('*.php')。
  • copy() / rename() / unlink():拷貝、移動/重命名、刪除。
  • mkdir() / rmdir():創建/刪除目錄(注意遞歸參數)。
  • fileperms() / chmod() / chown():權限讀取與修改。

實例 1:安全的目錄列表展示

<?php
function listDirectory(string $path): array {
    // 1. 路徑標準化與安全檢查(防止目錄遍歷攻擊)
    $realPath = realpath($path);
    $basePath = realpath(__DIR__ . '/public_files'); // 限制根目錄
    if (!$realPath || strpos($realPath, $basePath) !== 0) {
        throw new InvalidArgumentException('非法路徑');
    }

    $files = [];
    $dir = opendir($realPath);
    while (($entry = readdir($dir)) !== false) {
        if ($entry === '.' || $entry === '..') continue;
        $fullPath = $realPath . DIRECTORY_SEPARATOR . $entry;
        $files[] = [
            'name' => $entry,
            'path' => $fullPath,
            'is_dir' => is_dir($fullPath),
            'size' => is_file($fullPath) ? filesize($fullPath) : null,
            'mtime' => filemtime($fullPath),
            'perm' => substr(sprintf('%o', fileperms($fullPath)), -4),
        ];
    }
    closedir($dir);
    return $files;
}

// 使用
try {
    $list = listDirectory($_GET['dir'] ?? './public_files');
    header('Content-Type: application/json');
    echo json_encode($list, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
} catch (Exception $e) {
    http_response_code(400);
    echo $e->getMessage();
}

實例 2:帶錯誤處理的文件備份

<?php
function backupFile(string $source, string $destDir): bool {
    if (!is_file($source) || !is_readable($source)) {
        error_log("源文件不可讀:$source");
        return false;
    }
    if (!is_dir($destDir)) {
        mkdir($destDir, 0755, true);
    }
    $dest = $destDir . DIRECTORY_SEPARATOR . basename($source) . '_' . date('YmdHis');
    if (!@copy($source, $dest)) {
        error_log("拷貝失敗:$source -> $dest");
        return false;
    }
    // 可選:驗證文件完整性
    if (filesize($source) !== filesize($dest)) {
        unlink($dest);
        error_log("文件大小不一致,備份已回滾");
        return false;
    }
    return true;
}

權限管理要點

  • Web 服務器進程用戶(如 www-data)必須擁有目標目錄的 rwx 權限。
  • 避免將上傳目錄設為可執行(chmod 755 而非 777),並配置 Nginx/Apache 禁用腳本執行。
  • Linux 下 PHP 操作文件受 open_basedir 限制,需在 php.ini 配置允許路徑。

現代化替代:SplFileInfo / FilesystemIterator

$iterator = new FilesystemIterator('/var/www/uploads', FilesystemIterator::SKIP_DOTS);
foreach ($iterator as $fileinfo) {
    echo $fileinfo->getFilename() . ' - ' . $fileinfo->getSize() . ' bytes
'; }

物件導向風格更優雅,自動實現 Iterator 介面,適合大型項目。

copyright © 萬盛學電腦網 all rights reserved