$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);
}
| 現象 | 可能原因 | 解決方案 |
|---|---|---|
| Permission denied | 檔案唯讀/權限不足/被其他程序佔用 | chmod / 關閉佔用程序 / 權限提升 |
| Directory not empty | 直接對目錄用 unlink | 先遞迴刪除內容再用 rmdir |
| 無效果不報錯 | 路徑錯誤/相對路徑問題 | 使用絕對路徑 / realpath() 驗證 |