基本語法
bool unlink(string $filename, ?resource $context = null)
- 成功回傳
true,失敗回傳 false 並發出 E_WARNING。
$context 為串流上下文(少用)。
基本範例
<?php
$file = 'home/meeta/my.php';
if (unlink($file)) {
echo "檔案刪除成功。\n";
} else {
echo "刪除失敗:檔案不存在或權限不足。\n";
}
?>
進階:刪除前檢查檔案存在
<?php
$file = './test1.txt';
if (file_exists($file)) {
$result = unlink($file);
echo $result ? "刪除成功" : "刪除失敗(權限問題?)";
} else {
echo "檔案不存在,無需刪除。";
}
?>
file_exists() 注意事項
- 回傳
true 代表檔案或目錄存在。
- 受
open_basedir 限制。
- 結果會被快取,若同腳本中檔案被建立/刪除,需呼叫
clearstatcache()。
批次刪除目錄下所有檔案
<?php
function deleteFilesInDir(string $dir, string $pattern = '*'): int {
$deleted = 0;
$files = glob($dir . DIRECTORY_SEPARATOR . $pattern);
foreach ($files as $file) {
if (is_file($file)) {
if (unlink($file)) {
$deleted++;
} else {
error_log("無法刪除:$file");
}
}
}
return $deleted;
}
// 刪除 logs/ 目錄下所有 .log 檔
$count = deleteFilesInDir(__DIR__ . '/logs', '*.log');
echo "已刪除 $count 個檔案";
?>
遞迴刪除整個目錄樹
<?php
function removeDirectory(string $dir): bool {
if (!is_dir($dir)) return false;
$items = array_diff(scandir($dir), ['.', '..']);
foreach ($items as $item) {
$path = $dir . DIRECTORY_SEPARATOR . $item;
is_dir($path) ? removeDirectory($path) : unlink($path);
}
return rmdir($dir);
}
// 使用
removeDirectory(__DIR__ . '/cache');
?>
錯誤處理最佳實踐
<?php
function safeUnlink(string $path): bool {
// 清除 stat 快取確保 file_exists 即時
clearstatcache(true, $path);
if (!file_exists($path)) {
trigger_error("檔案不存在:$path", E_USER_WARNING);
return false;
}
if (!is_writable($path)) {
trigger_error("檔案不可寫入:$path", E_USER_WARNING);
return false;
}
$result = @unlink($path); // 抑制 warning,自行處理
if (!$result) {
trigger_error("刪除失敗:$path", E_USER_ERROR);
}
return $result;
}
?>
Windows 上的特殊問題
- 檔案被其他程序開啟時無法刪除(需關閉佔用程序)。
- 路徑長度限制(MAX_PATH 260 字元),長路徑需加
\\?\ 前綴。
- 大小寫不敏感,但實際檔案系統可能保留大小寫。
相關函數速查
| 函數 | 用途 |
unlink() | 刪除檔案 |
rmdir() | 刪除空目錄 |
file_exists() | 檢查檔案/目錄存在 |
is_file() | 確認是檔案(非目錄/連結) |
is_writable() | 確認可寫入(含刪除權限) |
clearstatcache() | 清除檔案狀態快取 |
glob() | 模式匹配取得檔案列表 |