2011-10-26 78 views
0

我有一個使用我的控制之外的流媒體服務器流式傳輸大型視頻文件,有時我想刪除的視頻文件。當文件碰巧被使用流式服務器的人查看時,PHP錯誤帶有「權限被拒絕」。在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說「一切都好」,直到重命名命令。重命名命令有從來沒有工作隨機機會。

我應該怎麼做與文件?

+0

那麼文件權限呢? –

+0

@KA_lin不是問題,當視頻沒有被流式傳輸時,重命名命令完美地起作用 – Tominator

+0

所以問題是什麼? –

回答

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

您正在鎖定文件。確保你如果調用成功再次解鎖(剛過echo "not locked!";

+0

更新我的代碼來解鎖文件,但它具有相同的效果 – Tominator

+0

您已經關閉了文件,你也解除了嗎? – fredley

+1

直接從PHP手冊中獲得:「鎖也是由fclose()釋放的(當腳本完成時它也被自動調用)。」 – Tominator

1

,因爲我看到的是,當你檢查,如果該文件被鎖定與flock你打開一個資源文件,但沒有關閉該文件的問題。所以文件現在被鎖定,你不能重命名它

+0

更新我的代碼來解鎖文件,但它具有相同的效果 – Tominator

+0

我想這就是原因其實 –

+0

@Tominator你也使用'FCLOSE()' – JRSofty

0

你不能刪除一個文件是流...如果你真的想...做一個副本,它的名稱,並把文件(原始)在堆棧(DB),並有一個cron作業什麼的把它刪除...

+0

不是問題,當視頻不被流,重命名命令完美的作品 – Tominator

+0

所以,即使你得到「未鎖定」的消息你還是不能老是重命名? –

+0

事實上,即使有消息「未鎖定」和當前的代碼示例,我也無法重命名/刪除。重命名發生在fclose之後,所以把它放在else分支中並沒有真正的區別。 – Tominator

-1

解決辦法是在這裏:

$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."; 
    } 
} 
相關問題