萬盛學電腦網

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

PHP 建立多層目錄的最佳實踐:mkdir 遞歸模式、權限控制、競態條件處理

前言

mkdir($path, 0755, true) 的第三個參數 recursive=true 讓多層目錄建立變得簡單,但生產環境仍需處理權限遺傳、umask 影響、競態條件、NFS 掛載延遲等細節。本文提供健壯的目錄建立工具函數與最佳實踐。

基本用法與陷阱

<?php
// 基本用法
mkdir('/var/www/storage/app/public/uploads/2024/03', 0755, true);

// 常見問題:
// 1. 權限不符預期:實際權限 = 0755 & ~umask()。預設 umask 0022 → 實際 0755;umask 0002 → 實際 0775。
// 2. 競態條件:多進程同時建立同目錄,可能拋出 "File exists" 警告。
// 3. NFS/網路檔案系統:mkdir 回傳 true 但目錄尚未對其他節點可見。
// 4. 符號連結:路徑包含 symlink 時行為不可預期。

健壯的目錄建立函數

<?php
/**
 * 安全建立多層目錄,處理競態條件、權限、NFS 延遲
 *
 * @param string $path 目標路徑
 * @param int $mode 權限模式(八進位),預設 0775
 * @param int $maxRetries 重試次數(NFS 延遲應對)
 * @param int $retryDelayUs 重試間隔微秒
 * @return bool 成功建立或已存在
 * @throws RuntimeException 無法建立且非已存在錯誤
 */
function ensureDirectory(string $path, int $mode = 0775, int $maxRetries = 3, int $retryDelayUs = 100000): bool {
    // 正規化路徑
    $path = rtrim($path, '/\\');
    if ($path === '') return true;

    // 檢查是否已存在(快速路徑)
    if (is_dir($path)) return true;

    // 嘗試建立
    $attempt = 0;
    while ($attempt <= $maxRetries) {
        $attempt++;
        // 使用 @ 抑制警告,自行判斷錯誤
        $result = @mkdir($path, $mode, true);
        if ($result) {
            // 修正權限(umask 可能導致實際權限不符)
            @chmod($path, $mode);
            return true;
        }

        $error = error_get_last();
        // 已存在視為成功(競態條件:其他進程剛建好)
        if ($error && str_contains($error['message'], 'File exists')) {
            if (is_dir($path)) {
                @chmod($path, $mode); // 確保權限正確
                return true;
            }
            // 同名檔案存在 → 錯誤
            throw new RuntimeException("路徑衝突:$path 已存在且非目錄");
        }

        // 最後一次嘗試仍失敗
        if ($attempt > $maxRetries) {
            throw new RuntimeException("建立目錄失敗:$path - " . ($error['message'] ?? '未知錯誤'));
        }

        // 短暫延遲後重試(應對 NFS 延遲)
        usleep($retryDelayUs);
    }
    return false; // 不會到達
}

權限最佳實踐

場景建議模式說明
Web 可寫入目錄(上傳、快取、日誌)0775擁有者/群組可寫,其他可讀。PHP-FPM 與部署用戶同群組。
敏感資料目錄(設定檔、金鑰)0750僅擁有者/群組可存取,其他無權限。
公開靜態資源(CSS、JS、圖片)0755全域可讀,僅擁有者可寫。
臨時目錄0777 + sticky bitchmod 1777,所有用戶可建檔但僅能刪除自己檔案。

關鍵原則:不要使用 0777。配置 PHP-FPM 以 www-data 用戶/群組運行,部署用戶加入同群組,目錄設為 0775 + setgid(chmod g+s),新建檔案自動繼承群組。

批次建立與效能

// 需建立大量已知結構目錄時,單次 mkdir 遞歸較慢
// 可改用系統指令(若允許 exec)
exec("mkdir -p '" . escapeshellarg($path) . "'", $output, $returnVar);
// 或並行建立獨立分支目錄
$dirs = ['/a/b/c', '/a/d/e', '/x/y/z'];
foreach ($dirs as $dir) {
    // 可用 parallel 擴展或多進程並行
    ensureDirectory($dir);
}

Laravel / Symfony 整合

// Laravel Filesystem
use Illuminate\Support\Facades\File;
File::ensureDirectoryExists($path, 0775, true, true); // 內建遞歸、權限、chmod

// Symfony Filesystem
use Symfony\Component\Filesystem\Filesystem;
$fs = new Filesystem();
$fs->mkdir($path, 0775); // 自動遞歸、自動 chmod、處理競態

總結

建立多層目錄看似簡單,生產環境需考量 umask、競態、NFS、權限繼承。封裝 ensureDirectory 函數統一處理錯誤重試、權限修正、路徑正規化,並遵循「最小權限原則」(避免 0777),是專案檔案系統操作的基石。

copyright © 萬盛學電腦網 all rights reserved