TarranJones
TarranJones

Reputation: 4242

What are all possible reasons for unlink to fail and how to check

I would like a list or code block of all necessary checks needed to prevent and unlink function from throwing an error. The more detailed the better as I am hoping this question will solve a lot of peoples issues.

Reasons for Errors

  1. File doesn't exist
  2. File Not Writable
  3. Containing Directory Not Writable @marc-anton-dahmen answer
  4. File open/in use

This is what I have so far

if(is_actually_file($file)){ 

    if(is_writable($file) && is_writable(dirname($file))) {

        unlink($file);

    } else {

        // insufficient file permissions
    }

} else {
    // file doesn't exist
}


function is_actually_file($file){

    clearstatcache(true, $file);
    return is_file($file);
}

What other reasons are there for failing and how to check for them?

unlink source code

Upvotes: 0

Views: 412

Answers (1)

Marc Anton Dahmen
Marc Anton Dahmen

Reputation: 1091

is_writable includes a file_exists check. But you have to check if the containing directory is writable as well. This should do it:

if (is_writable($file) && is_writable(dirname($file))) {
    unlink($file);
} else {
    //...
}

Upvotes: 1

Related Questions