萬盛學電腦網

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

PHP unlink 刪除檔案完整指南:單檔刪除、批次清理、遞迴刪除目錄與錯誤處理

基本用法

// 刪除單一檔案
$file = '/path/to/file.jpg';
if (file_exists($file)) {
    unlink($file) or die("刪除失敗: $file");
}

// 靜默刪除 (不報錯)
@unlink($file);

實務封裝:圖片刪除連帶縮圖

class ImageManager {
    private $path;
    private $pre_thumb = 'thumb_';
    private $pre_pic   = 'pic_';
    private $pic_count = 0;
    
    public function removePic(string $filename): bool|string {
        $mainFile  = $this->path . $filename;
        $thumbFile = $this->path . str_replace($this->pre_pic, $this->pre_thumb, $filename);
        
        $mainOk  = @unlink($mainFile);
        $thumbOk = @unlink($thumbFile);
        
        if ($mainOk && $thumbOk) {
            $this->pic_count--;
            return true;
        }
        
        // 部分失敗:嘗試回滾 (若主檔刪除成功但縮圖失敗,可選擇恢復或記錄)
        if ($mainOk && !$thumbOk) {
            // 記錄孤立主檔供人工處理
            error_log("孤立主檔: $mainFile");
        }
        
        return "!F"; // 刪除失敗代碼
    }
}

遞迴刪除非空目錄

function deleteDirectory(string $dir): bool {
    if (!is_dir($dir)) return false;
    
    $files = new RecursiveIteratorIterator(
        new RecursiveDirectoryIterator($dir, RecursiveDirectoryIterator::SKIP_DOTS),
        RecursiveIteratorIterator::CHILD_FIRST
    );
    
    foreach ($files as $file) {
        $path = $file->getPathname();
        $file->isDir() ? @rmdir($path) : @unlink($path);
    }
    
    return @rmdir($dir);
}

// 使用
deleteDirectory('/var/www/cache/old');

進階:安全刪除與審計

class SafeFileDeleter {
    private $auditLog = [];
    
    public function delete(string $path, bool $force = false): bool {
        $realPath = realpath($path);
        if (!$realPath) {
            $this->log("不存在: $path");
            return false;
        }
        
        // 安全檢查:防止目錄遍歷、限制在允許根目錄下
        $allowedRoot = realpath('/var/www/uploads');
        if (strpos($realPath, $allowedRoot) !== 0) {
            $this->log("拒絕刪除受保護路徑: $realPath");
            return false;
        }
        
        // 權限檢查
        if (!is_writable($realPath)) {
            $this->log("無寫入權限: $realPath");
            return false;
        }
        
        $result = is_dir($realPath) 
            ? $this->deleteDir($realPath) 
            : @unlink($realPath);
            
        $this->log(($result ? "成功" : "失敗") . ": $realPath");
        return $result;
    }
    
    private function deleteDir(string $dir): bool { /* 同上 */ }
    private function log(string $msg) { $this->auditLog[] = date('Y-m-d H:i:s') . " $msg"; }
    public function getAuditLog(): array { return $this->auditLog; }
}

常見錯誤與除錯

錯誤原因解決
Permission denied檔案擁有者非 PHP 執行用戶、目錄不可寫chown/chmod、ACL、php-fpm 用戶設定
Resource busy / Text file busy檔案被其他程序開啟 (如 Nginx 發送中)延遲刪除、lsof 排查、重啟服務
No such file路徑錯誤、相對/絕對路徑混淆用 realpath() 正規化、記錄完整路徑
Is a directory對目錄用 unlink用 rmdir() 或遞迴刪除

現代替代:Flysystem

use League\Flysystem\FilesystemAdapter;
$fs->delete('path/to/file.jpg');
$fs->deleteDirectory('path/to/dir');
copyright © 萬盛學電腦網 all rights reserved