Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: Check whether file can be deleted

Tags:

php

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.

like image 702
Roland Seuhs Avatar asked Jan 20 '26 14:01

Roland Seuhs


2 Answers

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.

like image 166
Striezel Avatar answered Jan 23 '26 04:01

Striezel


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.";
}
like image 38
Chukiat Kalambaheti Avatar answered Jan 23 '26 04:01

Chukiat Kalambaheti



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!