unlink() 刪除文件失敗,報 No such file or directory,往往不是權限問題,而是「隱形字符」或路徑解析差異導致。本文系統梳理排查思路。
Warning: unlink(user_logo/d4d84f383714d5f3.jpg) ... No such file or directory
關鍵線索: 是 UTF-8 BOM (Byte Order Mark) 的 HTML 實體編碼,說明文件名讀取時攜帶了不可見的 BOM 字符 \xEF\xBB\xBF。
$filename = preg_replace('/^\xEF\xBB\xBF/', '', $filename); 或 ltrim($filename, "\xEF\xBB\xBF")。__DIR__ . '/user_logo/' . $filename。if (file_exists($path)) unlink($path);。function safeUnlink($relativePath, $baseDir = __DIR__) {
$fullPath = $baseDir . '/' . ltrim($relativePath, '/');
$fullPath = preg_replace('/^\xEF\xBB\xBF/', '', $fullPath); // 去 BOM
if (file_exists($fullPath) && is_file($fullPath)) {
if (@unlink($fullPath)) {
return ['success' => true, 'path' => $fullPath];
}
return ['success' => false, 'error' => 'unlink_failed', 'path' => $fullPath];
}
return ['success' => false, 'error' => 'not_found', 'path' => $fullPath];
}
var_dump(bin2hex($filename)) 可見隱藏字符十六進制。realpath($path) 驗證路徑解析結果。open_basedir 限制是否阻斷訪問。「文件不存在」背後往往藏著編碼、路徑、上下文三類陷阱,逐層驗證方能根治。