Search code examples
phpunlink

Php unlink file which is in use situation?


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

Solution

  • 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.