Php 正在使用的情况下取消链接文件?

Php unlink file which is in use situation?

根据我的个人经验,您无法删除正在使用的内容,我认为如果目标文件正在使用,unlink() 将不起作用,您如何处理?

<?php unlink ("notes.txt"); // how to handle if file in use? ?>

unlink returns 可用于检测删除是否成功的布尔值:

<?php

$file = fopen('notes.txt','w');
fwrite($file,'abc123');

$resul = unlink("notes.txt"); // ◄■■■ ATTEMPT TO DELETE OPEN FILE.
if ( $resul )
     echo "File deleted";
else echo "File NOT deleted (file in use or protected)";

fclose($file);

?>    

您可能会在屏幕上看到一条警告消息,因此请关闭警告并让您的代码(if($resul))处理该问题。

编辑:

使用函数 is_writable 可以检测文件是否正在使用或受到保护,下一段代码显示如何:

<?php

$file = fopen("notes.txt","w"); // ◄■■■ OPEN FILE.
fwrite($file,"abc123");

$resul = unlink("notes.txt"); // ◄■■■ ATTEMPT TO DELETE FILE.
if ( $resul ) // ◄■■■ IF FILE WAS DELETED...
     echo "File deleted";
elseif ( is_writable( "notes.txt" ) ) // ◄■■■ IF FILE IS WRITABLE...
     echo "File NOT deleted (file in use)";
else echo "File NOT deleted (file protected)";

fclose($file);

?>    

要测试以前的代码,打开文件的属性并将其设置为只读和隐藏,然后 运行 代码。