unlink()删除文件,但返回false


unlink() deletes file but returns false

我有一个问题,无法解决。我试图删除一个文件并返回成功消息,但指示它删除文件,但返回false。这是我的代码:

if(unlink(".".MEDIA_PATH."/$av")){          
    exit(header("Location: page.php?&msg=success"));
}
else{
    exit(header("Location: page.php?msg=fail"));    
}

来自德国的丹帮助了我解决方案是:不要使用Windows进行编程,使用Linux:)错误是因为我在Windows操作系统上使用localhost

我对您的代码做了一些更改。

先检查文件是否存在,然后删除。

$file = '.' . MEDIA_PATH . '/' . $av;
if (file_exists($file)) {
    if (unlink($file)) {          
        header("Location: page.php?msg=success");
    } else {
        header("Location: page.php?msg=fail&reason=cannot-delete");
    }
} else {
    header("Location: page.php?msg=fail&reason=file-not-exists");
}
exit;

更新:

众所周知,unlink()有时会在windows系统上失败。

在使用"file_exists"函数删除文件之前,请确保文件存在("unlink"可能会在同时调用两个实例的情况下调用,但这对测试来说无关紧要)。

$filePath = "." . MEDIA_PATH . "/$av";
if( !file_exists($filePath) ) {
    echo "File does not exist: $filePath";
    exit(1);
} else if( unlink($filePath) ) {
    exit(header("Location: page.php?&msg=success"));
} else{
    exit(header("Location: page.php?msg=fail"));    
}

如果工作流出现故障,并且unlink函数被调用了两次,您会很容易注意到。

您还可以使用带有break的xdebug来测试您的代码。

我找到了一个解决方案,但它不是最好的。如果你有什么请帮我。

这是我的解决方案:

$del_file=".".MEDIA_PATH."/$av"; 
// Deleting file from server
@unlink($del_file); 
if(!file_exists($del_file)){                
    exit(header("Location: page.php?&msg=success"));
}
else{
    exit(header("Location: page.php?&msg=fail"));   
}

它仍然给我在unlink()上的错误false,所以我在unlink()上添加了@operator来屏蔽它,但这不是我想要的。这有关系吗,因为我在本地主机(windows)上,而不是在实时服务器上?

看起来func unlink()运行了两次,第一次删除文件,第二次返回错误,因为找不到指定的文件。

卢卡·罗戈维奇:

看起来func unlink()运行了两次,第一次删除文件和安全时间,因为找不到而返回错误指定的文件。

试试这个:

$filePath = "." . MEDIA_PATH . "/$av";
if( !filter_has_var(INPUT_GET, 'msg') ) {
    if( !file_exists ) {
        exit(header("Location: page.php?msg=fail&reason=file-does-not-exist")); 
    } else if( unlink($filePath) ) {
        exit(header("Location: page.php?&msg=success"));
    } else{
        exit(header("Location: page.php?msg=fail&reason=cannot-delete"));
    }
}

我相信"page.php"被调用了两次,"unlink"被调用两次。

条件"!filter_has_var(INPUT_GET,'msg')"可防止这种情况发生。

尽管如此,您应该理解"解决方案"为什么有效:使用浏览器中的"Inspect元素"分析重定向,并使用xdebug查看"unlink"是否被调用了两次。