I would like to know whether I can delete a file.
The function is_writable() does not work because it does not check whether the containing directory allows deletion of files.
I also cannot to use @unlink() because I first generate a list of deletable files and delete only a portion of them after doing some calculations.
The answers in this question also do not check whether the directory allows deletion of files: In PHP, check if a file can be deleted - so it seems that this simple question has not yet been answered, even after so many years.
As @apokryfos pointed out in comment, you need to have write permission on the file's parent directory to delete a file within that directory. Using that information a check could look like this:
if (is_writable(dirname("/path/to/the/file.ext")))
{
echo "File is deletable.";
}
else
{
echo "File cannot be deleted.";
}
The dirname() function gets the directory the file is located in. Then we can use is_writable() to check whether we have write permission on the directory.
The original answer by Striezel in 2018 has 1 missing if clause parentheses. The code should read:
if (is_writable(dirname("/path/to/the/file.ext")))
{
echo "File is deletable.";
}
else
{
echo "File cannot be deleted.";
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With