PHP 提供 unlink() 刪除檔案、rmdir() 刪除目錄。本文系統講解參數、返回值、錯誤處理、安全檢查與實戰模式。
unlink(string $filename, ?resource $context = null): bool
<?php
// 簡單刪除
unlink("test.txt"); // 成功返回 true,失敗 false
// 變數路徑
$file = "test.txt";
unlink($file);
?>
<?php
$file = "test.txt";
if (unlink($file)) {
echo "檔案 $file 刪除成功!";
} else {
echo "檔案 $file 刪除失敗!";
// 可檢查 error_get_last() 獲取詳細錯誤
}
?>
<?php
$myfile = "./test1.txt";
if (file_exists($myfile)) {
$result = unlink($myfile);
echo $result ? "刪除成功" : "刪除失敗: " . error_get_last()['message'];
} else {
echo "檔案不存在: $myfile";
}
?>
<?php
function deleteFiles(array $patterns): array {
$results = [];
foreach ($patterns as $pattern) {
$files = glob($pattern);
foreach ($files as $file) {
if (is_file($file)) {
$results[$file] = unlink($file);
}
}
}
return $results;
}
// 刪除所有 .tmp 和 .log 檔案
$results = deleteFiles(['*.tmp', '*.log', 'cache/*']);
print_r($results);
?>
rmdir(string $dirname, ?resource $context = null): bool
<?php
$dirname = 'testdir';
if (rmdir($dirname)) {
echo "目錄 $dirname 刪除成功";
} else {
echo "目錄 $dirname 刪除失敗: " . error_get_last()['message'];
}
?>
<?php
function deleteDirectory(string $dir): bool {
if (!is_dir($dir)) {
return false;
}
$items = scandir($dir);
foreach ($items as $item) {
if ($item === '.' || $item === '..') continue;
$path = $dir . DIRECTORY_SEPARATOR . $item;
if (is_dir($path)) {
deleteDirectory($path); // 遞歸刪除子目錄
} else {
unlink($path); // 刪除檔案
}
}
return rmdir($dir); // 最後刪除空目錄
}
// 使用
deleteDirectory('/path/to/directory');
?>
<?php
function deleteDirectoryModern(string $dir): void {
$files = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($dir, RecursiveDirectoryIterator::SKIP_DOTS),
RecursiveIteratorIterator::CHILD_FIRST // 先刪除子項
);
foreach ($files as $file) {
if ($file->isDir()) {
rmdir($file->getPathname());
} else {
unlink($file->getPathname());
}
}
rmdir($dir);
}
?>
<?php
function safeDelete(string $userInput, string $baseDir): bool {
// 解析真實路徑
$realBase = realpath($baseDir);
$realTarget = realpath($baseDir . DIRECTORY_SEPARATOR . $userInput);
// 確保目標在基礎目錄內
if ($realTarget === false || strpos($realTarget, $realBase) !== 0) {
throw new Exception("非法路徑訪問: $userInput");
}
return is_file($realTarget) ? unlink($realTarget) : deleteDirectory($realTarget);
}
?>
if (!is_writable($file)) {
throw new Exception("無寫入權限: $file");
}
flock() 或資料庫鎖防止競態刪除| 錯誤常數 | 值 | 含義 |
|---|---|---|
| E_WARNING | 2 | unlink/rmdir 失敗時觸發(權限、不存在、目錄非空) |
| ENOENT | 2 | 檔案/目錄不存在 |
| EACCES | 13 | 權限拒絕 |
| ENOTEMPTY | 39 | 目錄非空 |
| EISDIR | 21 | 對目錄使用 unlink() |
exec('rm -rf ...') (需極度謹慎、輸入消毒) 或背景任務隊列unlink() 會自動清除快取,但 file_exists() 多次調用需手動清除tmpfile() 創建的臨時檔案,關閉句柄或腳本結束自動刪除unlink() 刪除檔案,rmdir() 刪除空目錄RecursiveDirectoryIterator::CHILD_FIRST 遞歸模式