unlink(string $filename, resource $context = null): bool
刪除指定文件,成功返回 true,失敗返回 false(如文件不存在、權限不足)。
<?php
$file = 'data/temp.txt';
if (file_exists($file)) {
if (unlink($file)) {
echo "文件 $file 刪除成功";
} else {
echo "刪除失敗,請檢查權限";
}
} else {
echo "文件不存在";
}
?>
w 權限)。unlink 刪除鏈接本身,不影響目標文件。unlink 不能刪除目錄,需用 rmdir()(空目錄)或遞歸刪除函數。foreach (glob('cache/*.tmp') as $file) {
@unlink($file); // 抑制警告
}
unlink() 是 PHP 刪除文件的唯一標準函數,簡單直接。實際項目中建議先 file_exists 判斷,捕獲返回值處理異常,並注意權限與佔用問題。