我一直在试图弄清楚为什么unlink
不起作用。我尝试过堆栈溢出以前的问题和答案,但没有运气。需要删除的确切文件名是 'upload/test.png'
。首先,我检查了文件是否存在。
$filename = 'upload/test.png';
if(file_exists($filename)){
// file_exists returns true
if(is_writable($filename)){
// is_writable also returns true
if(unlink($filename)){
echo 'file deleted';
}
else{
echo 'cant delete file';
print_r(error_get_last());
// this gives me
// unlink() function.unlink: No such file or directory
}
}
}
改为提供完整路径,例如
$filename = dirname(__FILE__) . '/upload/test.png';
然后试试这个,
if (is_file($filename)) {
chmod($filename, 0777);
if (unlink($filename)) {
echo 'File deleted';
} else {
echo 'Cannot remove that file';
}
} else {
echo 'File does not exist';
}
如果您说一切正常并且没有权限问题,那么您也可以尝试以下方式:
unlink(realpath("upload/test.png"));
试试这个并发布你得到的输出(如果有的话)。
$filename = 'upload/test.png';
@unlink($filename);
if(is_file($filename)) {
echo "file was locked (or permissions error)";
}
我发现取消链接对编码很敏感。我也有这样的问题,但后来我使用了:
$filename= iconv("UTF-8", "Windows-1251", $filename);
这对我有用。