dongqian3198 2016-10-04 17:18
浏览 50
已采纳

Php unlink文件在使用情况?

In my personal experience, you cannot delete something that's in use, I think unlink() will not work if the target file is in use, how do you handle that?

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

1条回答 默认 最新

  • duan4739 2016-10-04 17:49
    关注

    unlink returns a boolean that you can use to detect if deletion was successful or not:

    <?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);
    
    ?>    
    

    You might see a warning message on screen, so turn off warnings and let your code (the if($resul)) handle the problem.

    Edit :

    It's possible to detect whether the file is in use or it is protected by using the function is_writable, next code shows how :

    <?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);
    
    ?>    
    

    To test previous code, open the properties of the file and set it to readonly and hidden, then run the code.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用