问题
I have a large video file that is streamed using a streaming server outside my control, and sometimes I want to delete the video file. When the file happens to be viewed by someone using the streaming server, PHP errors with "Permission denied".
I would like to check before attempting to delete if the file can be deleted or not. I do not want to actually try to delete the file and see if that fails, I would like to check beforehand.
This is my code so far:
$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);
The output I get when I stream video.flv while executing the code:
is writeable
not locked!
modification time has been changed to present time
PHP Warning: rename(video.flv,newvideoname.flv): Permission denied in ...
Sometimes I get:
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 ...
So sometimes the file cannot be locked by PHP and it cannot be touch()ed by PHP, and then of course the rename doesn't work, but sometimes PHP says "all is fine" until the rename command. The rename command has never worked by random chance.
What should I do with the file?
回答1:
if (!flock(fopen($file, 'a+'), LOCK_EX | LOCK_NB)) {
You are locking the file. Make sure you unlock it again if the call succeeds (just after echo "not locked!";
回答2:
The problem as I see it is that when you checked if the file is locked with flock
you opened a resource to the file but did not close the file. So the file is now locked and you can't rename it.
回答3:
You cannot delete a file that is streaming...if you REALLY WANT TO...make a copy, raname it, and put the file(original) in a stack(DB) and have a cron job or something to delete it...
回答4:
The solution is here :
$file = "test.pdf";
if (!is_file($file)) {
print "File doesn't exist.";
} else {
$fh = @fopen($file, "r+");
if ($fh) {
print "File is not opened and seems able to be deleted.";
fclose($fh);
} else {
print "File seems to be opened somewhere and can't be deleted.";
}
}
来源:https://stackoverflow.com/questions/7900936/in-php-check-if-a-file-can-be-deleted