在PHP中,检查是否可以删除文件

时间:2011-10-26 09:34:29

标签: php file delete-file

我有一个大型视频文件,使用我无法控制的流媒体服务器进行流式传输,有时我想删除该视频文件。当文件碰巧被使用流服务器的人查看时,PHP错误“权限被拒绝”。

我想在尝试删除之前检查是否可以删除文件。我不想实际尝试删除该文件,看看是否失败,我想事先检查。

到目前为止,这是我的代码:

$file = "video.flv";
$file2 = "newvideoname.flv";
clearstatcache();
if (is_writeable($file)) {
    echo "is writeable";
}
else {
    echo "is NOT writeable";
}
echo "\n";
$fh = fopen($file, 'a+');
if (!flock($fh, LOCK_EX | LOCK_NB)) {
    // file locked, do something else
    echo "is locked";
}
else {
    echo "not locked!";
}
fclose($fh);
echo "\n";
if (touch($file)) {
    echo "modification time has been changed to present time";
}
else {
    echo "Sorry, could not change modification time";
}
echo "\n";
rename($file, $file2);

我在执行代码时流式传输video.flv时得到的输出:

is writeable
not locked!
modification time has been changed to present time
PHP Warning:  rename(video.flv,newvideoname.flv): Permission denied in ...

有时我会:

is writeable
PHP Warning:  fopen(video.flv): failed to open stream: Permission denied ...
PHP Warning:  flock() expects parameter 1 to be resource, boolean given
is locked
PHP Warning:  fclose(): supplied argument is not a valid stream resource
PHP Warning:  touch(): Utime failed: Permission denied
Sorry, could not change modification time
PHP Warning:  rename(video.flv,newvideoname.flv): Permission denied ...

因此,有时文件无法被PHP锁定而且它无法通过PHP触摸(),然后当然重命名不起作用,但有时PHP在重命名命令之前说“一切正常”。重命名命令从不随机工作。

该怎么办?

4 个答案:

答案 0 :(得分:3)

if (!flock(fopen($file, 'a+'), LOCK_EX | LOCK_NB)) {

您正在锁定该文件。如果通话成功(在echo "not locked!";

之后),请务必再次将其解锁

答案 1 :(得分:1)

我看到的问题是,当您检查文件是否被flock锁定时,您打开了该文件的资源但未关闭该文件。因此该文件现已锁定,您无法重命名。

答案 2 :(得分:0)

您无法删除正在播放的文件...如果您真的想要...复制,拉扯它,并将文件(原始)放入堆栈(数据库)并拥有一个cron作业或其他内容删除它......

答案 3 :(得分:-1)

解决方案在这里:

driver.findElement(By.cssSelector("a.collection-item").id("3"));
// or
driver.findElement(By.xpath(".//*[@id='time']/a[3]")).click();
// or
Actions builder = new Actions(driver);
    builder.moveToElement(we1).click().build().perform();