萬盛學電腦網

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

PHP unlink 刪除檔案與目錄完整教學

unlink 基本用法

$myFile = "testFile.txt";
// 確保檔案未被開啟
if (file_exists($myFile)) {
    unlink($myFile); // 刪除檔案
    echo "檔案已刪除";
} else {
    echo "檔案不存在";
}

關鍵步驟:先關閉檔案控制代碼

$fh = fopen($myFile, 'w');
// ... 讀寫操作 ...
fclose($fh); // 必須先關閉
unlink($myFile); // 才能刪除

嘗試刪除開啟中的檔案會失敗(Windows 下尤其嚴格)。

刪除目錄

unlink 無法刪除非空目錄。需遞迴刪除內容後才能用 rmdir() 刪除目錄本身:

function deleteDirectory($dir) {
    if (!is_dir($dir)) return false;
    
    $items = scandir($dir);
    foreach ($items as $item) {
        if ($item === '.' || $item === '..') continue;
        $path = $dir . DIRECTORY_SEPARATOR . $item;
        is_dir($path) ? deleteDirectory($path) : unlink($path);
    }
    return rmdir($dir);
}

安全刪除檔案函數

function safeUnlink($path) {
    // 清除快取確保檢查準確
    clearstatcache(true, $path);
    
    if (!file_exists($path)) return true; // 已不存在視為成功
    if (is_dir($path)) return deleteDirectory($path);
    
    // 嘗試解除唯讀屬性(Windows)
    @chmod($path, 0777);
    
    return unlink($path);
}

常見問題排查

最佳實務

  • 刪除前記錄日誌(檔名、時間、操作者)
  • 重要資料實施軟刪除(移至回收區/標記 deleted)
  • 批次刪除時考慮效能,避免單次請求處理過多檔案
copyright © 萬盛學電腦網 all rights reserved
現象可能原因解決方案
Permission denied檔案唯讀/權限不足/被其他程序佔用chmod / 關閉佔用程序 / 權限提升
Directory not empty直接對目錄用 unlink先遞迴刪除內容再用 rmdir
無效果不報錯路徑錯誤/相對路徑問題使用絕對路徑 / realpath() 驗證