Suppress "No such file or directory" with unlink?

1.4k Views Asked by At

I'm using Sentry for monitoring errors on a website. I have a piece of code that gives me trouble, it is from an old Kohana (PHP framework) module.

Giving this code (which I edited):

if ($delete === TRUE)
{
    $file_tmp = $file->getRealPath();
    clearstatcache(TRUE, $file_tmp);
    if (file_exists($file_tmp))
    {
        return @unlink($file_tmp);
    }
    return FALSE;
}

How can I make it so it doesn't trigger errors like this on Sentry:

Warning: unlink(/var/www/my-hostname-files/application/cache/25/2530cfe0309c86c52f8dda53ca493f4cf72fdbd3.cache): No such file or directory

The original code was just the big IF and the unlink call but it seems somewhere between file_exists call and unlink, some other process deletes the file ?!

Thanks!

1

There are 1 best solutions below

0
Markus Zeller On BEST ANSWER

You can disable error reporting for a while and no need to force supress warnings.

Note: When you try to delete a directory, you must delete all files recursively inside, first.

if ($delete === TRUE)
{
    $file_tmp = $file->getRealPath();
    clearstatcache(TRUE, $file_tmp);
    if (file_exists($file_tmp))
    {
        // store current error reporting level
        $level = error_reporting();

        // turn completely off
        error_reporting(0);

        // unlink and store state
        $state = unlink($file_tmp);

        // restore error reporting level
        error_reporting($level);

        // return unlink state
        return $state;
    }
    return FALSE;
}