基本用法
// 刪除單一檔案
$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');