Search code examples
phpunlink

php file is writable but cannot be deleted


I am using this function. is_file and is_writable return true, but when I true to unlink, it gives an error. This is on windows server.

if(is_file($fileToDelete)) {
  if(is_writable($fileToDelete)) {
    unlink($fileToDelete);
  }
}

The file is a PDF document, which I have open. I thought is_writable would return false in this case, but it doesn't.

So how can I tell if a file can be deleted or not?

Thank you


Solution

  • What about doing it the other way around? Just try to delete the file and check whether it is really gone?

    @unlink($fileToDelete);
    
    if(is_file($fileToDelete)) {
       // file was locked (or permissions error)
    }
    

    Not sure whether this is workable in your specific case though, but judging by the code in your question this should be what you want.